Springboot 自定义全局异常处理

男娘i 2023-09-29 06:11 113阅读 0赞

自定义全局异常处理

  • 业务异常
  • 捕捉validation框架校验异常

业务异常

在项目根包目录下新建 exception.base 包
新建BaseException 继承 RuntimeException

  1. package com.ddz.errordemo.handler;
  2. /**
  3. * 基础异常类
  4. * @author Lenovo
  5. * @date 2022/4/26
  6. */
  7. public class BaseException extends RuntimeException {
  8. /**
  9. * 所属模块
  10. */
  11. private String module;
  12. /**
  13. * 错误码
  14. */
  15. private String code;
  16. /**
  17. * 错误码对应的参数
  18. */
  19. private Object[] args;
  20. /**
  21. * 错误消息
  22. */
  23. private String defaultMessage;
  24. public BaseException(String module, String code, Object[] args, String defaultMessage) {
  25. this.module = module;
  26. this.code = code;
  27. this.args = args;
  28. this.defaultMessage = defaultMessage;
  29. }
  30. public BaseException(String module, String code, Object[] args) {
  31. this(module, code, args, null);
  32. }
  33. public BaseException(String module, String defaultMessage) {
  34. this(module, null, null, defaultMessage);
  35. }
  36. public BaseException(String code, Object[] args) {
  37. this(null, code, args, null);
  38. }
  39. public BaseException(String defaultMessage) {
  40. this(null, null, null, defaultMessage);
  41. }
  42. public String getModule() {
  43. return module;
  44. }
  45. public void setModule(String module) {
  46. this.module = module;
  47. }
  48. public String getCode() {
  49. return code;
  50. }
  51. public void setCode(String code) {
  52. this.code = code;
  53. }
  54. public Object[] getArgs() {
  55. return args;
  56. }
  57. public void setArgs(Object[] args) {
  58. this.args = args;
  59. }
  60. public String getDefaultMessage() {
  61. return defaultMessage;
  62. }
  63. public void setDefaultMessage(String defaultMessage) {
  64. this.defaultMessage = defaultMessage;
  65. }
  66. }

根据自己的需要新建业务异常类

  1. package com.ddz.errordemo.exception;
  2. import com.ddz.errordemo.exception.base.BaseException;
  3. /**
  4. * 用户信息异常类
  5. */
  6. public class UserException extends BaseException
  7. {
  8. private static final long serialVersionUID = 1L;
  9. public UserException(String code, Object[] args)
  10. {
  11. super("user", code, args, null);
  12. }
  13. }

在项目根包目录下新建 exception.handler包;
新建RestExceptionHandler 异常处理类

  1. package com.ddz.errordemo.exception.handler;
  2. import com.ddz.errordemo.exception.base.BaseException;
  3. import org.springframework.web.bind.annotation.ExceptionHandler;
  4. import org.springframework.web.bind.annotation.RestControllerAdvice;
  5. import javax.servlet.http.HttpServletRequest;
  6. /**
  7. * @author Lenovo
  8. * @date 2022/4/26
  9. */
  10. @RestControllerAdvice
  11. public class RestExceptionHandler {
  12. @ExceptionHandler(Exception.class)
  13. public Object exception(HttpServletRequest request, Exception e) {
  14. return request.getRequestURL() + "全局异常" + e.getMessage();
  15. }
  16. @ExceptionHandler(NullPointerException.class)
  17. public Object nullException(Exception e) {
  18. return "空指针" + e.getMessage();
  19. }
  20. @ExceptionHandler(RuntimeException.class)
  21. public Object busException(BaseException e) {
  22. return "模块" + e.getModule() + "异常码:" + e.getCode() + "异常信息:" + e.getMessage();
  23. }
  24. }

捕捉validation框架校验异常

如果springboot 版本高于3.5.1 需要导入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-validation</artifactId>
  4. </dependency>

在异常类中添加方法

  1. import com.ddz.project.common.exception.code.BusinessException;
  2. import com.ddz.project.common.exception.code.BaseResponseCode;
  3. import com.ddz.project.common.exception.code.DataResult;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.validation.ObjectError;
  6. import org.springframework.web.bind.MethodArgumentNotValidException;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.RestControllerAdvice;
  9. import javax.validation.ConstraintViolation;
  10. import javax.validation.ConstraintViolationException;
  11. import java.util.List;
  12. import java.util.Set;
  13. /**
  14. * RestExceptionHandler
  15. *
  16. * @author Lenovo
  17. * @version V1.0
  18. * @date 2020年3月18日
  19. */
  20. @RestControllerAdvice
  21. @Slf4j
  22. public class RestExceptionHandler {
  23. /**
  24. * 自定义全局异常处理
  25. */
  26. @ExceptionHandler(value = BusinessException.class)
  27. Object businessExceptionHandler(BusinessException e) {
  28. log.error("BusinessException:{}", e.getMessageCode(), e);
  29. return e.getMessageCode()+e.getDetailMessage();
  30. }
  31. /**
  32. * 处理validation 框架异常, 需要controller添加@Validated注解
  33. */
  34. @ExceptionHandler(MethodArgumentNotValidException.class)
  35. Object methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
  36. log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
  37. List<ObjectError> errors = e.getBindingResult().getAllErrors();
  38. // String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
  39. return errors.get(0).getDefaultMessage();
  40. }
  41. /**
  42. * 校验List<entity>类型, 需要controller添加@Validated注解
  43. * 处理Validated List<entity> 异常
  44. */
  45. @ExceptionHandler
  46. public Object handle(ConstraintViolationException exception) {
  47. log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", exception, exception);
  48. Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
  49. StringBuilder builder = new StringBuilder();
  50. for (ConstraintViolation<?> violation : violations) {
  51. builder.append(violation.getMessage());
  52. break;
  53. }
  54. return builder.toString();
  55. }
  56. }

发表评论

表情:
评论列表 (有 0 条评论,113人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java全局异常处理-定义异常处理

    > 哈喽!大家好,我是旷世奇才李先生 > 文章持续更新,可以微信搜索【小奇JAVA面试】第一时间阅读,回复【资料】更有我为大家准备的福利哟,回复【项目】获取我为大家准备的项