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等字段.单个 ...
- 配置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 注解 ...
- springboot工程添加404页面
首先在/src/main/resources下创建文件夹/public/error 在文件夹里创建html页面,jsp页面不可以. <html> <body> <img ...
- SpringBoot学习15:springboot异常处理方式5(通过实现HandlerExceptionResolver类)
修改异常处理方式4中的全局异常处理controller package com.bjsxt.exception; import org.springframework.context.annotati ...
- SpringBoot学习14:springboot异常处理方式4(使用SimpleMappingExceptionResolver处理异常)
修改异常处理方法3中的全局异常处理Controller即可 package bjsxt.exception; import org.springframework.context.annotation ...
随机推荐
- 在.NET Core程序中设置全局异常处理
以前我们想设置全局异常处理只需要这样的代码: AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledExc ...
- paip.python连接mysql最佳实践o4
paip.python连接mysql最佳实践o4 python连接mysql 还使用了不少时间...,相比php困难多了..麻烦的.. 而php,就容易的多兰.. python标准库没mysql库,只 ...
- Common Converters in WPF/Silverlight
using System; using System.ComponentModel; using System.Globalization; using System.Windows.Data; na ...
- 【随手记-有空整理】Linux随手记
1. CentOS6.5安装g++:yum install gcc-c++ 注意如果写成yum install g++会提示No package g++ available. 2. XShell下打开 ...
- 【代码笔记】Web-JavaScript-JavaScript JSON
一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- Java并发——Fork/Join框架与ForkJoinPool
为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/ShiJiaqi. http://www.cnblogs.com/shijiaqi1066/p/4631466. ...
- 下拉选择框QCombox
下拉列表框样式如图: 字体列表框样式: import sys from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QFontCo ...
- 转载:删除github上文件夹的两种方式
http://www.jianshu.com/p/286be61bb9b8 删除github上文件夹的两种方式(解决已经加入ignore的文件夹无法从远程仓库删除的问题) 如果此文件夹已被加入git追 ...
- JavaScript标准对象
1.Date var now = new Date(); now; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST) now.getFullYear(); // 2 ...
- C#解析数组形式的json数据
在学习时遇到把解析json数据的问题,网上也搜了很多资料才得以实现,记录下来以便翻阅. 1. 下载开源的类库Newtonsoft.Json(下载地址http://json.codeplex.com/, ...