Spring Boot实现异常处理
Spring Boot实现异常处理
Spring提供了一种使用@ControllerAdvice处理异常的非常有用的方法。 我们通过实现一个ControlerAdvice类,来处理控制器类抛出的所有异常。
//全局异常捕捉处理@ControllerAdvicepublicclassCustomExceptionHandler{@ResponseBody@ExceptionHandler(value=Exception.class)publicMaperrorHandler(Exception ex){Map map=newHashMap();
map.put("code",400);//判断异常的类型,返回不一样的返回值if(exinstanceofMissingServletRequestParameterException){
map.put("msg","缺少必需参数:"+((MissingServletRequestParameterException) ex).getParameterName());}elseif(exinstanceofMyException){
map.put("msg","这是自定义异常");}return map;}}
//自定义异常类@DatapublicclassMyExceptionextendsRuntimeException{privatelong code;privateString msg;publicMyException(Long code,String msg){super(msg);this.code= code;this.msg= msg;}publicMyException(String msg){super(msg);this.msg= msg;}}
@RestControllerpublicclassTestController{@RequestMapping("testException")publicStringtestException()throwsException{thrownewMissingServletRequestParameterException("name","String");}@RequestMapping("testMyException")publicStringtestMyException()throwsMyException{thrownewMyException("i am a myException");}}