一:说明
1.说明
这个注解是用于写一个异常捕获的处理类。
这里介绍全局捕获异常,自定义异常捕获
2.ps
在这里,顺便写一下基础的自定义异常类,以后方便用于业务异常继承
二:全局异常捕获
1.处理类
package com.jun.web.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; @ControllerAdvice @ResponseBody public class GlobalExceptionAdviceHandle { /** * 全局异常捕获 * @param ex * @return */ @ExceptionHandler(value = Exception.class) public Map<String, Object> errorHandle(Exception ex){ Map<String, Object> map = new HashMap<>(); map.put("code","-1"); map.put("msg", ex.getMessage()); return map; } }
2.controller控制类
package com.jun.web.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * 验证异常捕获注解 */ @RestController public class MakeErrorController { @GetMapping("/global") public String calc(){ int num=3/0; return "success"; } }
3.访问
三:自定义异常
1.异常基础类
1 package com.jun.web.exception; 2 3 import lombok.Data; 4 5 /** 6 * 基础异常类 7 */ 8 @Data 9 public class BaseException extends RuntimeException{ 10 //异常码 11 private String code; 12 private String msg; 13 BaseException(){} 14 public BaseException(String code, String msg){ 15 this.code=code; 16 this.msg=msg; 17 } 18 }
2.自定义异常处理类
1 package com.jun.web.exception; 2 3 import org.springframework.web.bind.annotation.ControllerAdvice; 4 import org.springframework.web.bind.annotation.ExceptionHandler; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 import java.util.HashMap; 8 import java.util.Map; 9 10 @ControllerAdvice 11 @ResponseBody 12 public class GlobalExceptionAdviceHandle { 13 /** 14 * 全局异常捕获 15 * @param ex 16 * @return 17 */ 18 @ExceptionHandler(value = Exception.class) 19 public Map<String, Object> errorHandle(Exception ex){ 20 Map<String, Object> map = new HashMap<>(); 21 map.put("code","-1"); 22 map.put("msg", ex.getMessage()); 23 return map; 24 } 25 26 /** 27 * 针对BaseException的异常捕获 28 * @param ex 29 * @return 30 */ 31 @ExceptionHandler(value = BaseException.class) 32 public Map<String, Object> errorHandle(BaseException ex){ 33 Map<String, Object> map = new HashMap<>(); 34 map.put("code",ex.getCode()); 35 map.put("msg", ex.getMsg()); 36 return map; 37 } 38 }
3.测试
package com.jun.web.controller; import com.jun.web.exception.BaseException; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * 验证异常捕获注解 */ @RestController public class MakeErrorController { @GetMapping("/global") public String calc(){ int num=3/0; return "success"; } @GetMapping("/global/err") public String throwErr(){ throw new BaseException("20000","普通的错误"); } }
4.结果