springboot:拦截全局异常处理(自定义拦截格式)

亦凉 2022-12-29 12:41 279阅读 0赞

主要有两个注解

  1. @RestControllerAdvice 或者 @ControllerAdvice
  2. @ExceptionHandler(RuntimeException.class)
  3. /**
  4. * 全局异常处理器
  5. *
  6. */
  7. @RestControllerAdvice
  8. public class GlobalExceptionHandler
  9. {
  10. private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  11. /**
  12. * 运行异常
  13. */
  14. @ExceptionHandler(RuntimeException.class)
  15. public AjaxResult runtimeException(RuntimeException e)
  16. {
  17. return AjaxResult.error(e.getMessage());
  18. }
  19. /**
  20. * 基础异常
  21. */
  22. @ExceptionHandler(BaseException.class)
  23. public AjaxResult baseException(BaseException e)
  24. {
  25. return AjaxResult.error(e.getMessage());
  26. }
  27. /**
  28. * 业务异常
  29. */
  30. @ExceptionHandler(CustomException.class)
  31. public AjaxResult businessException(CustomException e)
  32. {
  33. if (StringUtils.isNull(e.getCode()))
  34. {
  35. return AjaxResult.error(e.getMessage());
  36. }
  37. return AjaxResult.error(e.getCode(), e.getMessage());
  38. }
  39. @ExceptionHandler(NoHandlerFoundException.class)
  40. public AjaxResult handlerNoFoundException(Exception e)
  41. {
  42. log.error(e.getMessage(), e);
  43. return AjaxResult.error(HttpStatus.NOT_FOUND, "路径不存在,请检查路径是否正确");
  44. }
  45. @ExceptionHandler(AccessDeniedException.class)
  46. public AjaxResult handleAuthorizationException(AccessDeniedException e)
  47. {
  48. log.error(e.getMessage());
  49. return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
  50. }
  51. }

发表评论

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

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

相关阅读