【转载】Springboot2.3.5实现全局异常处理
参考
- springBoot2.3配置全局捕获异常
- springboot 使用logback记录日志,并简单配置application.properties
- 2021-04-07Springboot两种获取get所有URL路径中的参数 getQueryString 和 @RequestParam
环境
- Springboot 2.3.5
- slf4j (自带)
步骤
- 在 exception/ 创建全局异常处理类 GlobalExceptionHandler.java
/**
* @Author 夏秋初
* @Date 2021/8/6 23:04
* @ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
* @ControllerAdvice 可以指定扫描范围
*/
@ControllerAdvice(basePackages = "com.xxx.suddenlynlinelearningplatform.controller")
public class GlobalExceptionHandler {
/**
* 日志类
*/
public static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 获取请求信息
*/
@Autowired
HttpServletRequest httpServletRequest;
/**
* @ExceptionHandler 表示拦截异常
*/
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public ResponseEntity<ResponseBodyUtils<Map<String, String>>> errorResult(RuntimeException e) {
// 通过判断异常是否属于自定义的异常类,进行相应的处理
// if(e instanceof JwtAuthException){
// System.out.println("权限拦截器异常");
// }
/**
* 错误类名
* e.getClass().getName();
* 错误内容
* e.getMessage();
*/
//
String errorCode = UUID.randomUUID().toString();
// 记录日志
LOGGER.error(
"\r\nERROR_CODE:"+
errorCode+
"\r\nURL:"+
httpServletRequest.getRequestURI()+
"\r\nMETHOD:"+
httpServletRequest.getMethod()+
"\r\nPARAMETERS:"+
httpServletRequest.getQueryString()+
"\r\nERRPR_TYPE:"+
e.getClass().getName()+
"\r\n ERROR_MESSAGE:"+e.getMessage());
//
Map<String, String> map = new HashMap<String, String>(){{
put("error_code", errorCode);
}};
//
System.out.println("拦截到异常:"+e.getClass().getName());
System.out.println("异常内容:"+e.getClass());
//
return ResponseEntity.status(500).body(new ResponseBodyUtils<Map<String, String>>(map));
}
}
- exception / 创建自定义异常类 JwtAuthException
public class JwtAuthException extends RuntimeException{
private static final long serialVersionUID = 1L;
private Integer httpCode = 200;
// 可以判断是自定义异常的时候获取对应的属性,来优化响应内容
private String responseMessage = "权限验证失败";
}
- 在控制器内编写报错
@Api(tags = "测试类", value = "测试类")
@RestController
@RequestMapping("/test")
public class Test {
@Autowired
StudentService studentService;
@RequestMapping(value = "index", method = RequestMethod.GET)
public ResponseBodyUtils<Student> index() throws JwtAuthException{
throw new JwtAuthException();
// return new ResponseBodyUtils( studentService.findById(18));
}
}
- 测试结果

博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/15110806.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/articles/15110806.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。

浙公网安备 33010602011771号