GlobalExceptionHandler.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.genersoft.iot.vmp.conf;
  2. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  3. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  4. import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.http.HttpStatus;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.security.authentication.BadCredentialsException;
  10. import org.springframework.web.bind.annotation.ExceptionHandler;
  11. import org.springframework.web.bind.annotation.ResponseStatus;
  12. import org.springframework.web.bind.annotation.RestControllerAdvice;
  13. /**
  14. * 全局异常处理
  15. */
  16. @RestControllerAdvice
  17. public class GlobalExceptionHandler {
  18. private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  19. /**
  20. * 默认异常处理
  21. * @param e 异常
  22. * @return 统一返回结果
  23. */
  24. @ExceptionHandler(Exception.class)
  25. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  26. public WVPResult<String> exceptionHandler(Exception e) {
  27. logger.error("[全局异常]: ", e);
  28. return WVPResult.fail(ErrorCode.ERROR500.getCode(), e.getMessage());
  29. }
  30. /**
  31. * 自定义异常处理, 处理controller中返回的错误
  32. * @param e 异常
  33. * @return 统一返回结果
  34. */
  35. @ExceptionHandler(ControllerException.class)
  36. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  37. public ResponseEntity<WVPResult<String>> exceptionHandler(ControllerException e) {
  38. return new ResponseEntity<>(WVPResult.fail(e.getCode(), e.getMsg()), HttpStatus.OK);
  39. }
  40. /**
  41. * 登陆失败
  42. * @param e 异常
  43. * @return 统一返回结果
  44. */
  45. @ExceptionHandler(BadCredentialsException.class)
  46. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  47. public ResponseEntity<WVPResult<String>> exceptionHandler(BadCredentialsException e) {
  48. return new ResponseEntity<>(WVPResult.fail(ErrorCode.ERROR100.getCode(), e.getMessage()), HttpStatus.OK);
  49. }
  50. }