GlobalExceptionHandler.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.tofly.scada.common;
  2. import com.tofly.common.core.entity.ResultRespone;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.core.annotation.Order;
  6. import org.springframework.validation.BindException;
  7. import org.springframework.web.bind.MethodArgumentNotValidException;
  8. import org.springframework.web.bind.annotation.ControllerAdvice;
  9. import org.springframework.web.bind.annotation.ExceptionHandler;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. /**
  12. * @author HaiQiu
  13. * @date 2021/11/19
  14. * 全局异常处理器
  15. */
  16. @ControllerAdvice
  17. @Order(1)
  18. public class GlobalExceptionHandler {
  19. private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);
  20. @ResponseBody
  21. @ExceptionHandler(Exception.class)
  22. public ResultRespone exception(Exception e) {
  23. // e.printStackTrace();
  24. LOGGER.debug(e.getMessage());
  25. if (e instanceof MethodArgumentNotValidException) {
  26. MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
  27. String errMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
  28. return ResultRespone.failed(errMsg);
  29. }
  30. if (e instanceof BindException){
  31. BindException ex = (BindException) e;
  32. String errMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
  33. return ResultRespone.failed(errMsg);
  34. }
  35. return ResultRespone.failed(e.getMessage());
  36. }
  37. }