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实例的时 ...
随机推荐
- _BSMachError: (os/kern) invalid capability (20) _BSMachError: (os/kern) invalid name (15) 问题的解决
在项目中突然遇到一个问题,也就是_BSMachError: (os/kern) invalid capability (20) _BSMachError: (os/kern) invalid name ...
- springmvc中的异常处理方法
//1.自定义异常处理类 2.编写异常处理器 3.配置异常处理器 package com.hope.exception;/** * 异常处理类 * @author newcityma ...
- 我的第一篇博客blog,笑哭
我的第一篇博客blog Markdown学习 一级标题:#加一个空格 加 文字, 二级标题:加2个##以此类推 字体 粗体:hello world!字体前有二个星号,字体后有二个星号 斜体:hello ...
- 使用MyBatis框架时发现的一些小bug
在大配置MyBatis.xml中: 不能有空节点属性 ,否则启动服务器后点击登录没有反应. 异常问题: ause: java.sql.SQLException: Value '0000-00-00 ...
- HashMap的putAll方法介绍说明
jdk1.8 使用putAll时,新map中的值仅为旧map值所对应对象的引用,并不会产生新对象. 如下,使用for循环赋值! public void putAll(Map<? extends ...
- 20 个 .NET 6 新增的 API
DateOnly & TimeOnly .NET 6 引入了两种期待已久的类型 - DateOnly 和 TimeOnly, 它们分别代表DateTime的日期和时间部分. DateOnly ...
- 微信浏览器打开H5页面右上角隐藏转发功能
js设置转发开关 document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { WeixinJSBridge. ...
- linux下编译php扩展
1 在pecl.php.net搜索你需要的php扩展 2 在解压后的扩展目录运行phpize 3 执行编译./configure --with-php-config=/usr/local/php/bi ...
- [BUUCTF]REVERSE——[GXYCTF2019]luck_guy
[GXYCTF2019]luck_guy 附件 步骤: ida载入,shift+f12查看程序里的字符串,看到了关于flag的提示 双击跟进跳转,ctrl+x找到关键函数 flag是由f1和f1拼接而 ...
- [ZJCTF 2019]EasyHeap
目录 逆向分析 create 函数 edit 函数 delete 函数 利用思路 exp 脚本 get flag 内容来源 逆向分析 -------------------------------- ...