springboot异常处理之404
ps: 推荐一下本人的通用后台管理项目crowd-admin 以及newbee-mall增强版,喜欢的话给个star就好
源码分析
在springboot中默认有一个异常处理器接口ErrorContorller,该接口提供了getErrorPath()方法,此接口的BasicErrorController实现类实现了getErrorPath()方法,如下:
/*
* AbstractErrorController是ErrorContoller的实现类
*/
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
...
@Override
public String getErrorPath() {
return this.errorProperties.getPath();
}
@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, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
@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, isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
....
}
errorProperties类定义如下:
public class ErrorProperties {
/**
* Path of the error controller.
*/
@Value("${error.path:/error}")
private String path = "/error";
...
}
由此可见,springboot中默认有一个处理/error映射的控制器,有error和errorHtml两个方法的存在,它可以处理来自浏览器页面和来自机器客户端(app应用)的请求。
当用户请求不存在的url时,dispatcherServlet会交由ResourceHttpRequestHandler映射处理器来处理该请求,并在handlerRequest方法中,重定向至/error映射,代码如下:
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// For very general mappings (e.g. "/") we need to check 404 first
Resource resource = getResource(request);
if (resource == null) {
logger.debug("Resource not found");
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
return;
}
...
}
getResource(request)会调用this.resolverChain.resolveResource(request, path, getLocations())方法,getLocations()方法返回结果如下:
接着程序会执行到getResource(pathToUse, location)方法如下:
@Nullable
protected Resource getResource(String resourcePath, Resource location) throws IOException {
// 新建一个resource对象,url为 location + resourcePath,判断此对象(文件)是否存在
Resource resource = location.createRelative(resourcePath);
if (resource.isReadable()) {
if (checkResource(resource, location)) {
return resource;
}
else if (logger.isWarnEnabled()) {
Resource[] allowedLocations = getAllowedLocations();
logger.warn("Resource path \"" + resourcePath + "\" was successfully resolved " +
"but resource \"" + resource.getURL() + "\" is neither under the " +
"current location \"" + location.getURL() + "\" nor under any of the " +
"allowed locations " + (allowedLocations != null ? Arrays.asList(allowedLocations) : "[]"));
}
}
return null;
}
在resource.isReadable()中,程序会在locations目录中寻找path目录下文件,由于不存在,返回null。
最终也就导致程序重定向至/error映射,如果是来自浏览器的请求,也就会返回/template/error/404.html页面,所以对于404请求,只需要在template目录下新建error目录,放入404页面即可。
使用注意
- 在springboot4.x中我们可以自定义
ControllerAdvice注解 +ExceptionHandler注解来处理不同错误类型的异常,但在springboot中404异常和拦截器异常由spring自己处理。
springboot异常处理之404的更多相关文章
- Springboot异常处理和自定义错误页面
1.异常来源 要处理程序发生的异常,首先需要知道异常来自哪里? 1.前端错误的的请求路径,会使得程序发生4xx错误,最常见的就是404,Springboot默认当发生这种错误的请求路径,pc端响应的页 ...
- SpringBoot异常处理统一封装我来做-使用篇
SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...
- nginx反向代理部署springboot项目报404无法加载静态资源
问题:nginx反向代理部署springboot项目报404无法加载静态资源(css,js,jpg,png...) springboot默认启动端口为8080,如果需要通过域名(不加端口号)直接访问s ...
- SpringBoot异常处理(二)
参数校验机制 JSR-303 Hibernate 参数接收方式: URL路径中的参数 {id} (@PathVariable(name="id") int-whatever) UR ...
- 配置springboot在访问404时自定义返回结果以及统一异常处理
在搭建项目框架的时候用的是springboot,想统一处理异常,但是发现404的错误总是捕捉不到,总是返回的是springBoot自带的错误结果信息. 如下是springBoot自带的错误结果信息: ...
- 【使用篇二】SpringBoot异常处理(9)
异常的处理方式有多种: 自定义错误页面 @ExceptionHandler注解 @ControllerAdvice+@ExceptionHandler注解 配置SimpleMappingExcepti ...
- SpringBoot 异常处理
异常处理最佳实践 根据我的工作经历来看,我主要遵循以下几点: 尽量不要在代码中写try...catch.finally把异常吃掉. 异常要尽量直观,防止被他人误解 将异常分为以下几类,业务异常,登录状 ...
- springBoot异常处理
1.status=404 Whitelabel Error Page Whitelabel Error Page This application has no explicit mapping fo ...
- springboot访问请求404问题
新手在刚接触springboot的时候,可能会出现访问请求404的情况,代码没问题,但就是404. 疑问:在十分确定代码没问题的时候,可以看下自己的包是不是出问题了? 原因:SpringBoot 注解 ...
随机推荐
- 笨方法学python笔记
编程是什么 编程就是通过输出一种语言给计算机"听",命令其去执行相应的操作. 我们称我们给计算机下达的命令称为指令.一般说程序就是有多个指令构成的. 计算机需要使用非常多的电路来实 ...
- linux下安装Zookeeper 3.4.14
1.下载Zookeeper 3.4.14(https://zookeeper.apache.org/) wget https://mirror.bit.edu.cn/apache/zookeeper/ ...
- Springboot websocket学习Demo
使用的是springboot2.1.4版本 <parent> <groupId>org.springframework.boot</groupId> <art ...
- Vue--子组件互相传值,子组件来回传值,传值反复横跳
Vue--子组件传值,子组件来回传值,子组件传值反复横跳 我不不仅要子组件之间直接传值,我还要传过去再传回来,传回来再传过去,子组件直接反复横跳 解决问题 给组件传值,并不知道改值的校验结果 同一个组 ...
- 安卓和ios的app证书过期的相关问题汇总
一,ios的APP的发布流程请见:ios的APP的发布流程 http://www.jianshu.com/p/b1b77d804254 这篇文章写得很好很全面 二,app证书过期了怎么办: IOS的情 ...
- 公司项目适配IOS9总结
1.JSONKit 项目在xcode7 IOS9 开发环境上报错,不能进行JSONSring和JSONData的使用 .在真机上没有问题,在模拟器上put和post数据适合JSONKit报空对象野指针 ...
- windows 上的MySQL默认字符集设置踩过的坑
前言: 前几天刚买了新电脑,装上MySQL有几天了,今天没事试了一下,发现默认字符集没有修改,还是默认的latin1,折腾了大半天,终于搞好了. 这是我成功设置后的结果图: 命令式直接在MySQL界面 ...
- 微服务之服务治理_Eureka
首先需要明确,不管是什么事物需要"治理",那一定是该事物存在一定问题.比如环境治理.那么服务,或者说微服务为什么需要治理?对于服务来说,如果它承担的业务职责简单,那其实治理的必要性 ...
- iOS label 添加删除线(删划线)遇到的坑
1.添加删划线方法遇到的问题 -(void)lastLabelDeal:(NSString *)str1 string:(NSString *)str2 label:(UILabel *)label{ ...
- Error:(12, 24) 警告: [deprecation] android.hardware中的Camera已过时.android
问题:android studio编译项目时出现: Error:(12, 24) 警告: [deprecation] android.hardware中的Camera已过时 解决:(只是让其不提示) ...