springboot使用@ControllerAdvice 捕抓全局异常

发布时间:2022-03-01 13:11:49 作者:yexindonglai@163.com 阅读(681)

使用方法很简单

  1. package com.icode.common.web.handler;
  2. import com.icode.common.constant.exception.LoginException;
  3. import com.xd.core.common.command.ResponseCommand;
  4. import com.xd.core.common.error.ErrorMsg;
  5. import com.xd.core.common.utils.WebUtils;
  6. import org.springframework.web.bind.annotation.ControllerAdvice;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. /**
  10. * <全局异常捕捉,,注意:作为一个@ControllerAdvice, GlobalExceptionHandler.java要单独存放文件夹
  11. * 或者已有bean的文件夹,否则和其他非bean文件放在一起就识别不出来>
  12. **/
  13. @ControllerAdvice
  14. public class GlobalExceptionHandler {
  15. /**
  16. * <当springboot项目出现运行时异常都会进入此方法>
  17. */
  18. @ExceptionHandler(value=Exception.class)
  19. @ResponseBody
  20. public ResponseCommand exceptionHandle(RuntimeException runtimeException){
  21. //打印异常信息
  22. runtimeException.printStackTrace();
  23. //返回错误信息给接口调用者
  24. return "{"errcode":"100","errMsg":"请求异常"}";
  25. }
  26. /**
  27. * <自定义异常捕捉>
  28. *
  29. */
  30. @ExceptionHandler(LoginException.class)
  31. @ResponseBody
  32. public ResponseCommand exceptionLogin(RuntimeException loginException){
  33. //打印异常信息
  34. loginException.printStackTrace();
  35. //返回错误信息给接口调用者
  36. return "{"errcode":"100","errMsg":"请求异常"}";
  37. }
  38. }

注意: 抛出异常时必须抛出 RuntimeException 才能捕捉到,

  1. @PostMapping(value = "article/validate/postArticle")
  2. public String saveArticle1(String token ,ArticleRequestCommand command) throws Exception{
  3. //RuntimeException 异常可正常捕捉
  4. throw new RuntimeException("可以捕捉的异常");
  5. //ControllerAdvice 无法捕捉Exception异常
  6. throw new Exception("无法捕捉的异常");
  7. return "succ";
  8. }

另外,自定义异常也必须继承 RuntimeException  异常,否则也是无法捕捉的

  1. package com.icode.common.constant.exception;
  2. import lombok.Data;
  3. /**
  4. * <自定义异常,必须继承 RuntimeException ,@ControllerAdvice才能捕捉到>
  5. *
  6. **/
  7. @Data
  8. public class LoginException extends RuntimeException {
  9. public LoginException() {
  10. }
  11. private Integer status;
  12. public LoginException(String message) {
  13. super(message);
  14. }
  15. public LoginException(Integer status,String message) {
  16. super(message);
  17. this.status = status;
  18. }
  19. }

 

关键字SpringBoot