BizExceptionHandler.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package easydo.technology.config.exception;
  2. import easydo.technology.exception.BizException;
  3. import lombok.extern.log4j.Log4j2;
  4. import org.springframework.http.HttpStatus;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.validation.BindException;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.RestControllerAdvice;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. /**
  12. * 处理Controller抛出的异常*
  13. * @author tianyf
  14. */
  15. @RestControllerAdvice
  16. @Log4j2
  17. public class BizExceptionHandler {
  18. /**
  19. * 处理业务异常 (BizException)
  20. * 返回 400 错误
  21. */
  22. @ExceptionHandler(BizException.class)
  23. public ResponseEntity<Object> handleBizException(BizException e) {
  24. log.error("[ 业务异常捕获 ] " + e.getMessage());
  25. Map<String, Object> vo = new HashMap<>();
  26. vo.put("success", false);
  27. vo.put("message", e.getMessage());
  28. vo.put("error", "");
  29. return new ResponseEntity<>(vo, HttpStatus.BAD_REQUEST);
  30. }
  31. /**
  32. * 处理所有不可知的系统异常 (Exception)
  33. * 返回 500 错误
  34. */
  35. @ExceptionHandler(Exception.class)
  36. public ResponseEntity<Object> handleException(Exception e) {
  37. log.error("[ 系统异常捕获 ] ", e);
  38. Map<String, Object> vo = new HashMap<>();
  39. vo.put("success", false);
  40. vo.put("message", "系统错误");
  41. vo.put("error", e.getMessage() != null ? e.getMessage() : e.getClass().getName());
  42. return new ResponseEntity<>(vo, HttpStatus.INTERNAL_SERVER_ERROR);
  43. }
  44. /**
  45. * 为 @NotNull / @NotEmpty / @NotBlank 提供异常后的消息抛出*
  46. * @param bindException
  47. * @return
  48. */
  49. @ExceptionHandler({BindException.class})
  50. public ResponseEntity<Object> throwCustomException(BindException bindException){
  51. log.error("[ @Vaild异常捕获 ] " + bindException.getMessage());
  52. Map<String, Object> vo = new HashMap<>();
  53. vo.put("success", false);
  54. vo.put("message", bindException.getBindingResult().getFieldError().getDefaultMessage());
  55. vo.put("error", "参数校验失败");
  56. return new ResponseEntity<>(vo, HttpStatus.BAD_REQUEST);
  57. }
  58. }