回顾

我在之前发布了一篇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异常的捕获的更多相关文章

  1. Spring系列之JDBC对不同数据库异常如何抽象的?

    前言 使用Spring-Jdbc的情况下,在有些场景中,我们需要根据数据库报的异常类型的不同,来编写我们的业务代码.比如说,我们有这样一段逻辑,如果我们新插入的记录,存在唯一约束冲突,就会返回给客户端 ...

  2. Spring系列(七) Spring MVC 异常处理

    Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...

  3. 朱晔和你聊Spring系列S1E6:容易犯错的Spring AOP

    阅读PDF版本 标题有点标题党了,这里说的容易犯错不是Spring AOP的错,是指使用的时候容易犯错.本文会以一些例子来展开讨论AOP的使用以及使用过程中容易出错的点. 几句话说清楚AOP 有关必要 ...

  4. Spring系列(六):Spring事务源码解析

    一.事务概述 1.1 什么是事务 事务是一组原子性的SQL查询,或者说是一个独立的工作单元.要么全部执行,要么全部不执行. 1.2 事务的特性(ACID) ①原子性(atomicity) 一个事务必须 ...

  5. Spring 系列: Spring 框架简介 -7个部分

    Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...

  6. [Spring MVC] - 500/404错误处理

    Spring MVC中404 找不到页面错误可以直接使用web.xml中配置: 在<web-app/>节点内加入: <error-page> <error-code> ...

  7. Spring 系列: Spring 框架简介(转载)

    Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...

  8. Spring系列

    Spring系列之访问数据库   阅读目录 一.概述 二.JDBC API的最佳实践 三.Spring对ORM的集成 回到顶部 一.概述 Spring的数据访问层是以统一的数据访问异常层体系为核心,结 ...

  9. Spring系列之DI的原理及手动实现

    目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 前言 在上一章中,我们介绍和简单实现了容器的部分功能,但是这里还留下了很多的问题.比如我们在构造bean实例的时 ...

随机推荐

  1. 隐藏状态栏后tableview自动上移20个像素的问题

    最近在开发过程中碰到一个很奇怪的问题,将状态栏隐藏掉之后,页面上的tableView会自动上移20个像素. 这是因为在iOS7.0之后,系统会自动调整scrollView的layout 和 conte ...

  2. binlog2sql 解析日志失败 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte

    python35 ./binlog2sql.py -h... -P... -u... -p... -B --start-file="mysql-bin.091940" --star ...

  3. Linux:-e、-d、-f、-L、-r、-w、-x、-s、-h、

    -e filename 如果 filename存在,则为真 -d filename 如果 filename为目录,则为真 -f filename 如果 filename为常规文件,则为真 -L fil ...

  4. Dubbo声明式缓存

    为了进一步提高消费者对用户的响应速度,减轻提供者的压力,Dubbo提供了基于结果的声明式缓存.该缓存是基于消费者端的,所以使用很简单,只需修改消费者配置文件,与提供者无关 一.创建消费者07-cons ...

  5. Redis缓存穿透、缓存击穿以及缓存雪崩

    作为一个内存数据库,redis也总是免不了有各种各样的问题,这篇文章主要是针对其中三个问题进行讲解:缓存穿透.缓存击穿和缓存雪崩.并给出一些解决方案.这三个问题是基本问题也是面试常问问题. 这篇文章我 ...

  6. centos7 docker 修改Nginx文件

    1.docker 安装 nginx : docker安装Nginx还是很简单的,可以参考百度文章 ,或者参照docker安装mysql :https://www.cnblogs.com/jonrain ...

  7. 【C/C++】引用&的含义/语法/作为函数参数/函数返回值/本质/常量引用

    含义 引用不产生副本,只是给原变量起了别名. 对引用变量的操作就是对原变量的操作. 基本语法 数据类型 &别名 = 原名 e.g. int a = 10; int &b = a; // ...

  8. 了解C#的Expression

    我们书接上文,我们在了解LINQ下面有说到在本地查询IEnumerbale主要是用委托来作为传参,而解析型查询 IQueryable则用Expression来作为传参: public static I ...

  9. 【.NET 与树莓派】控制彩色灯带(WS28XX)

    彩色灯带,相信不用老周多说,大家都知道,没准你家里的灯墙里面就有.老周的茅屋是早期建造的,所以没有预留的灯槽,明灯的话是不好看的,因此老周家里没使用灯带.不过,像柜子后面,显示器后面,书桌边沿这些地方 ...

  10. CPU的负载

    目录 一.简介 二.合理的负载 一.简介 使用top或者uptime命令可以看到cpu平均负载,1,5,15分钟 平均负载包括以下几个部分: 正在运行的进程.正在使用cpu做计算的进程,ps看到R 也 ...