2.spring系列之404异常的捕获
回顾
我在之前发布了一篇spring统一返回的文章,最后提到是无法捕获404异常的,这里我们先来测试一下
@RestController
public class TestController {
@GetMapping("/test")
public String insert22() {
return "hello";
}
}
浏览器请求试一下 http://localhost:8080/xxx 报错
# Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Dec 29 10:14:36 CST 2021
There was an unexpected error (type=Not Found, status=404).
springboot的处理方式
springboot处理这个404的异常是在 BasicErrorController中处理的
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
...........
@Override
public String getErrorPath() {
return null;
}
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections
.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
// 包含请求头 "Accept": "application/json" 会往这里走
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<>(status);
}
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
.............
}
只要请求路径/error就可以进去到errorHtml这个方法,在浏览器请求http://localhost:8080/error就可以进入这个方法
解决方案
我这使用的springboot的版本为2.3.7.RELEASE
方案1:重写/error的请求
这种方案会直接舍弃掉HTML响应方式,但是前后端分离模式下,后端已经很少使用ModelAndView了
@Controller
public class NoFoundController extends AbstractErrorController {
public NoFoundController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
/**
* 默认路径/error,可以通过server.error.path配置
*/
@RequestMapping(("${server.error.path:/error}"))
public ResponseEntity<Map<String, Object>> notFoundError(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>(3);
HttpStatus status = getStatus(request);
map.put("code", status.value());
map.put("data", null);
map.put("message", status.toString());
return new ResponseEntity<>(map, status);
}
/**
* 在springboot2.3.0新增了server.error.path进行配置,这个废弃使用了,之前版本可以直接通过设置这个返回值修改默认/error的路径
*/
@Override
public String getErrorPath() {
return null;
}
}
方案2:重写BasicErrorController中的错误处理
这种方式无法将HTML响应的也改成了json返回,请求中要有"Accept": "application/json"才能走json响应
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyBasicErrorController extends BasicErrorController {
public MyBasicErrorController(ServerProperties serverProperties) {
// import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
super(new DefaultErrorAttributes(), serverProperties.getError());
}
/**
* JSON响应
*/
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
HttpStatus status = getStatus(request);
map.put("code", status.value());
map.put("data", null);
map.put("message", status.toString());
return new ResponseEntity<>(map, status);
}
/**
* HTML响应,根据需求处理自己处理
*/
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
return super.errorHtml(request, response);
}
}
其中MyBasicErrorController的构造函数可以参考spring自动装配ErrorMvcAutoConfiguration中的传值
//源码:
public class ErrorMvcAutoConfiguration {
private final ServerProperties serverProperties;
public ErrorMvcAutoConfiguration(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
}
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
// ErrorAttributes
return new DefaultErrorAttributes();
}
@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes,
ObjectProvider<ErrorViewResolver> errorViewResolvers) {
// serverProperties.getError
return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
errorViewResolvers.orderedStream().collect(Collectors.toList()));
}
........
}
最后附上完整代码:
@Getter
public class BusinessException extends RuntimeException {
private Integer code;
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(String message) {
super(message);
}
}
--------------------------------------------------------------------------------------------
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalException {
@ExceptionHandler(value = BusinessException.class)
public ResponseModel<Void> businessExceptionError(BusinessException e) {
log.error("业务异常", e);
if (e.getCode() != null) {
return ResponseModel.error(e.getCode(), e.getMessage());
}
return ResponseModel.error(e.getMessage());
}
@ExceptionHandler(value = Exception.class)
public ResponseModel<Void> exceptionError(Exception e) {
log.error("系统异常", e);
return ResponseModel.error();
}
}
--------------------------------------------------------------------------------------------
@Getter
public enum ResponseEnum {
SUCCESS(0, "OK"),
PARAMETER_ERROR(1,"参数异常"),
NO_FOUND(404,"not found"),
SYSTEM_ERROR(500, "服务器异常,请联系管理员");
ResponseEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
private final Integer code;
private final String message;
}
--------------------------------------------------------------------------------------------
public class ResponseModel<T> {
private Integer code;
private String message;
private T data;
public ResponseModel(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static ResponseModel<Void> ok() {
return ok(null);
}
public static <T> ResponseModel<T> ok(T data) {
return new ResponseModel<>(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage(), data);
}
public static <T> ResponseModel<T> ok(T data, String message) {
return new ResponseModel<>(ResponseEnum.SYSTEM_ERROR.getCode(), message, data);
}
public static ResponseModel<Void> error(Integer statusCode, String message) {
return new ResponseModel<>(statusCode, message, null);
}
public static ResponseModel<Void> error(String message) {
return error(ResponseEnum.SYSTEM_ERROR.getCode(), message);
}
public static ResponseModel<Void> error() {
return error(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage());
}
}
--------------------------------------------------------------------------------------------
@Controller
public class NoFoundController extends AbstractErrorController {
public NoFoundController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
/**
* 默认路径/error,可以通过server.error.path配置
*/
@RequestMapping(("${server.error.path:/error}"))
public ResponseEntity<Map<String, Object>> notFoundError(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>(3);
HttpStatus status = getStatus(request);
map.put("code", status.value());
map.put("data", null);
map.put("message", status.toString());
return new ResponseEntity<>(map, status);
}
/**
* 在springboot2.3.0新增了server.error.path进行配置,这个废弃使用了,之前版本可以直接通过设置这个返回值修改默认/error的路径
*/
@Override
public String getErrorPath() {
return null;
}
}
感谢各位小伙伴阅读到最后,如有错误,敬请指正。
2.spring系列之404异常的捕获的更多相关文章
- Spring系列之JDBC对不同数据库异常如何抽象的?
前言 使用Spring-Jdbc的情况下,在有些场景中,我们需要根据数据库报的异常类型的不同,来编写我们的业务代码.比如说,我们有这样一段逻辑,如果我们新插入的记录,存在唯一约束冲突,就会返回给客户端 ...
- Spring系列(七) Spring MVC 异常处理
Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...
- 朱晔和你聊Spring系列S1E6:容易犯错的Spring AOP
阅读PDF版本 标题有点标题党了,这里说的容易犯错不是Spring AOP的错,是指使用的时候容易犯错.本文会以一些例子来展开讨论AOP的使用以及使用过程中容易出错的点. 几句话说清楚AOP 有关必要 ...
- Spring系列(六):Spring事务源码解析
一.事务概述 1.1 什么是事务 事务是一组原子性的SQL查询,或者说是一个独立的工作单元.要么全部执行,要么全部不执行. 1.2 事务的特性(ACID) ①原子性(atomicity) 一个事务必须 ...
- Spring 系列: Spring 框架简介 -7个部分
Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...
- [Spring MVC] - 500/404错误处理
Spring MVC中404 找不到页面错误可以直接使用web.xml中配置: 在<web-app/>节点内加入: <error-page> <error-code> ...
- Spring 系列: Spring 框架简介(转载)
Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...
- Spring系列
Spring系列之访问数据库 阅读目录 一.概述 二.JDBC API的最佳实践 三.Spring对ORM的集成 回到顶部 一.概述 Spring的数据访问层是以统一的数据访问异常层体系为核心,结 ...
- Spring系列之DI的原理及手动实现
目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 前言 在上一章中,我们介绍和简单实现了容器的部分功能,但是这里还留下了很多的问题.比如我们在构造bean实例的时 ...
随机推荐
- 给webapp加上一个apk外壳
原文:http://blog.csdn.net/cmyh100/article/details/77862962 1.在Android Studio里创建一个项目 2.创建MyApplication. ...
- zabbix之监控MySQL
#:先配置MySQL的主从 #:安装Percona Monitoring Plugins (地址:https://www.percona.com/downloads/)#:我安在从库,监控哪个就安哪个 ...
- MyBatis(4):使用limit实现分页
用limit实现分页,首先要创建一个Maven项目,搭建好mybatis的实验环境,并且连接好数据库 代码 1,编写dao接口 UserMapper //查询全部用户实现分页 List<User ...
- Java知识点总结——IO流框架
IO框架 一.流的概念 概念:内存与存储设备之间传输数据的通道. 二.流的分类 按方向分类: 输入流:将<存储设备>中的内容读入到<内存>中 输出流:将<内存>中的 ...
- Mybatis-plus报Invalid bound statement (not found)错误
错误信息 org.springframework.security.authentication.InternalAuthenticationServiceException: Invalid bou ...
- [BUUCTF]PWN——roarctf_2019_easy_pwn(详解)
roarctf_2019_easy_pwn 附件 步骤: 例行检查,64位程序,保护全开 试运行一下程序,看看大概的情况,经典的堆块的菜单 64位ida载入,改了一下各个选项的函数名,方便看程序(按N ...
- Table.FirstN保留前面N….First…(Power Query 之 M 语言)
数据源: "姓名""基数""个人比例""个人缴纳""公司比例""公司缴纳"&qu ...
- generating project in interactive mode
解决方案:加个参数 -DarchetypeCatalog=internal 让它不要从远程服务器上取catalog
- Spring Security Filter 学习笔记
过滤器可以简单理解成用于拦截请求,并执行相应逻辑的代码. 在Spring Security架构中实现过滤器 在SpringSecurity中,可以通过实现 javax.servlet 包中的 Filt ...
- Chrome导出导入书签
Chrome导出标签 Chrome导入书签