Spring Boot如何实现统一异常处理呢?
下文笔者讲述SpringBoot中实现统一异常处理的方法分享,如下所示:
测试Controller
实现思路: 使用SpringBoot中@ControllerAdvice注解 即可处理所有控制器抛出的异常例:
//全局异常捕捉处理 @ControllerAdvice public class CustomExceptionHandler { @ResponseBody @ExceptionHandler(value = Exception.class) public Map errorHandler(Exception ex) { Map map = new HashMap(); map.put("code", 400); //判断异常的类型,返回不一样的返回值 if(ex instanceof MissingServletRequestParameterException){ map.put("msg","缺少必需参数:"+((MissingServletRequestParameterException) ex).getParameterName()); } else if(ex instanceof MyException){ map.put("msg","这是自定义异常"); } return map; } } //自定义异常类 @Data public class MyException extends RuntimeException { private long code; private String msg; public MyException(Long code, String msg){ super(msg); this.code = code; this.msg = msg; } public MyException(String msg){ super(msg); this.msg = msg; } }
测试Controller
@RestController public class TestController { @RequestMapping("testException") public String testException() throws Exception{ throw new MissingServletRequestParameterException("name","String"); } @RequestMapping("testMyException") public String testMyException() throws MyException{ throw new MyException("i am a myException"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。