404错误

404错误是不经过Controller的,所以使用@ControllerAdvice或@RestControllerAdvice无法获取到404错误

springboot2处理404错误的两种方式

第一种:直接配置

#出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true

这种方式不太适用实际开发,比如和swagger集成时,访问/swagger-ui.html会出现404异常

第二种:继承ErrorController来处理错误

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @Controller
public class MyErrorController implements ErrorController { @RequestMapping("/error")
public String handleError(HttpServletRequest request){
//获取statusCode:401,404,500
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if(statusCode == 500){
return "/error/500";
}else if(statusCode == 404){
//对应的是/error/404.html、/error/404.jsp等,文件位于/templates下面
return "/error/404";
}else if(statusCode == 403){
return "/403";
}else{
return "/500";
} } @Override
public String getErrorPath() {
return "/error";
}
}
import com.bettn.common.util.Result;
import com.bettn.common.util.WebUtils;
import org.apache.shiro.ShiroException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* 全局异常捕获处理
*/
@RestControllerAdvice
public class ExceptionControllerAdvice {
private static final Logger logger= LoggerFactory.getLogger(ExceptionControllerAdvice.class); // 捕捉shiro的异常
@ExceptionHandler(ShiroException.class)
public Result handle401() {
return new Result(401,"您没有权限访问!",null);
} // 捕捉其他所有异常
@ExceptionHandler(Exception.class)
public Object globalException(HttpServletRequest request, HandlerMethod handlerMethod, Throwable ex) {
if(WebUtils.isAjax(handlerMethod)){
return new Result(getStatus(request).value(), "访问出错,无法访问: " + ex.getMessage(), null);
}else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/error/500"); //这里需要在templates文件夹下新建一个/error/500.html文件用作错误页面
modelAndView.addObject("errorMsg",ex.getMessage());
return modelAndView;
} } /**
* 判断是否是Ajax请求
*
* @param request
* @return
*/
public boolean isAjax(HttpServletRequest request) {
return (request.getHeader("X-Requested-With") != null &&
"XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
}
// @ExceptionHandler(Exception.class)
// public Result globalException(HttpServletRequest request, Throwable ex) {
// return new Result(getStatus(request).value(),"访问出错,无法访问: " + ex.getMessage(),null);
// } /**
* 获取响应状态码
* @param request
* @return
*/
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
} /**
* 捕捉404异常,这个方法只在配置
* spring.mvc.throw-exception-if-no-handler-found=true来后起作用
*
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public Result handle(HttpServletRequest request,NoHandlerFoundException e) {
System.out.println(12);
return new Result(404,"没有【"+request.getMethod()+"】"+request.getRequestURI()+"方法可以访问",null);
}
}

这个异常类与ExceptionControllerAdvice连用,ExceptionControllerAdvice类除了不能处理404异常以外,其他异常都可以处理,其中

globalException异常这个方法会捕获500错误,导致MyErrorController无法捕获到500错误,从而跳转到500页面,也就是说MyErrorController在这个项目中

只能捕获404异常

500异常捕获

500异常分为ajax和直接跳转500页面

具体的异常捕获,代码如何下:


// 捕捉其他所有异常
@ExceptionHandler(Exception.class)
public Object globalException(HttpServletRequest request, HandlerMethod handlerMethod, Throwable ex) {
if(WebUtils.isAjax(handlerMethod)){
return new Result(getStatus(request).value(), "访问出错,无法访问: " + ex.getMessage(), null);
}else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/error/500"); //这里需要在templates文件夹下新建一个/error/500.html文件用作错误页面
modelAndView.addObject("errorMsg",ex.getMessage());
return modelAndView;
} }
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
public class WebUtils extends org.springframework.web.util.WebUtils {
/**
* 判断是否ajax请求
* spring ajax 返回含有 ResponseBody 或者 RestController注解
* @param handlerMethod HandlerMethod
* @return 是否ajax请求
*/
public static boolean isAjax(HandlerMethod handlerMethod) {
ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
if (null != responseBody) {
return true;
}
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
Class<?> beanType = handlerMethod.getBeanType();
responseBody = AnnotationUtils.getAnnotation(beanType, ResponseBody.class);
if (null != responseBody) {
return true;
}
return false;
} public static String getCookieValue(HttpServletRequest request, String cookieName) {
Cookie cookie=getCookie(request, cookieName);
return cookie==null?null:cookie.getValue();
} public static void removeCookie(HttpServletResponse response, String cookieName) {
setCookie(response, cookieName, null, 0); } public static void setCookie(HttpServletResponse response, String cookieName, String cookieValue,
int defaultMaxAge) {
Cookie cookie=new Cookie(cookieName,cookieValue);
cookie.setHttpOnly(true);
cookie.setPath("/");
cookie.setMaxAge(defaultMaxAge);
response.addCookie(cookie);
} }

TIP

404、500页面需要放在/templates下,且确认配置了视图,如jsp、thymeleaf等,否则也会出现找不到页面,例如集成thymeleaf

依赖

<!-- thymeleaf模板引擎和shiro框架的整合,这个是与shiro集成的,一般不整合shiro就不需要这个依赖 -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>${thymeleaf.extras.shiro.version}</version>
</dependency>
<!-- SpringBoot集成thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置

spring:
# 模板引擎
thymeleaf:
mode: HTML5
encoding: utf-8
# 禁用缓存
cache: false

404、500页面地址(目录结构)

src/main/resources/templates/error/404.html

src/main/resources/templates/error/500.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>500</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body> <!--
直接使用${el}无法解析出el的值
${errorMsg}
--> <h3>糟糕! 服务器出错啦~~(>_<)~~</h3>
<div>
异常信息如下:<br/>
<p th:text="${errorMsg}"></p>
</div>
</body>
</html>

参考:https://www.jianshu.com/p/8d41243e7fba

springboot 2.x处理404、500等异常的更多相关文章

  1. C# MVC模式 404 500页面设置方法

    <customErrors mode="On" defaultRedirect="Controllers/Action"> <error st ...

  2. java异常处理及400,404,500错误处理

        java代码中经常碰到各种需要处理异常的时候,比如什么IOException  SQLException  NullPointException等等,在开发web项目中,遇到异常,我现在做的就 ...

  3. HTML状态码大全(301,404,500等)

    HTML状态码大全(301,404,500等)HTML状态码大全(301,404,500等)HTML状态码大全(301,404,500等)HTML状态码大全(301,404,500等) 这些状态码被分 ...

  4. idea启动springboot+jsp项目出现404

    场景:用IntelliJ IDEA 启动 springBoot项目访问出现404,很皮,因为我用eclipse开发时都是正常的,找了很久,什么加注释掉<scope>provided< ...

  5. Spring MVC自定义403,404,500状态码返回页面

    代码 HTTP状态码干货:http://tool.oschina.net/commons?type=5 import org.springframework.boot.web.servlet.erro ...

  6. Springboot解决资源文件404,503等特殊报错,无法访问

    Springboot解决资源文件404,503等特殊报错 原文链接:https://www.cnblogs.com/blog5277/p/9324609.html 原文作者:博客园--曲高终和寡 ** ...

  7. Django 编写自定义的 404 / 500 报错界面

    Django 编写自定义的 404 / 500 报错界面 1. 首先 setting.py 文件中的 debug 参数设置成 false ,不启用调试. DEBUG = False 2. 在 temp ...

  8. 解决spring boot中rest接口404,500等错误返回统一的json格式

    在开发rest接口时,我们往往会定义统一的返回格式,列如: { "status": true, "code": 200, "message" ...

  9. apache 网页301重定向、自定义400/403/404/500错误页面

    首先简单介绍一下,.htaccess文件是Apache服务器中的一个配置文件(Nginx服务器没有),它负责相关目录下的网页配置.通过对.htaccess文件进行设置,可以帮我们实现:网页301重定向 ...

随机推荐

  1. experiment : 在私有堆和默认进程堆中, 测试能分配的堆空间总和, 每次能分配的最大堆空间

    实验环境: Win7X64Sp1 + vs2008,  物理内存16GB. 实验结论: *  进程堆的最大Size并没有使用完剩余的物理内存    *  每次能分配的最大堆空间接近2M, 不管是私有堆 ...

  2. p2p-如何拯救k8s镜像分发的阿喀琉斯之踵

    K8s的出现为PaaS行业的发展打了一针兴奋剂,Docker+k8s的技术路线已经成为了容器云的主流.尤其针对大流量,大弹性的应用场景来说,k8s将其从繁杂的运维.部署工作中彻底拯救出来.然而事情往往 ...

  3. JSON排序

    //排序之前 var arrs=[{"PageID":"1"},{"PageID":"10"},{"PageI ...

  4. PAT 1021-1030 题解

    早期部分代码用 Java 实现.由于 PAT 虽然支持各种语言,但只有 C/C++标程来限定时间,许多题目用 Java 读入数据就已经超时,后来转投 C/C++.浏览全部代码:请戳 本文谨代表个人思路 ...

  5. docker入门2:基础操作(1)

    -- 列出所有的容器 docker ps -a  (没有-a就是只列出启动的) -- 开启/关闭/移除容器 docker start|stop|rm CONTAINER_ID|CONTAINER_NA ...

  6. phpcms视图查询数据

    {pc:get sql="SELECT * FROM phpcms WHERE id in ($id) ORDER BY listorder ASC LIMIT 0, 1--"re ...

  7. 开源库(要不要重新制造轮子)—— C/C++、Java、Python

    谷歌近期开源的SLAM方案:Cartographer Boost:准标准的C++库. Eigen3: 准标准的线性代数库. Lua:非常轻量的脚本语言,主要用来做Configuration Ceres ...

  8. 不使用运算符(+、-、*、/) 来进行四则运算(C#)

    最近在LeetCode 上刷题,遇到一个非常有趣的题目,题目的大概意思就是在不使用运算符的情况下实现两个数的加法...原题点这里>>> 说实话,刚看到这题目,我是一脸懵逼的. 后来仔 ...

  9. 通过浏览器调用Android要么iOS应用

    在做移动应用的单点登录时间,需要点击浏览器中启动链接APP和参数传递APP其中,用于处理相应的接口,现在,通过浏览器调用Android和iOS在应用过程中实现理清固化博客.为了查询. 一:通过浏览器调 ...

  10. 一次 .NET Core 中玩锁的经历:ManualResetEventSlim, Semaphore 与 SemaphoreSlim

    最近同事对  .net core memcached 缓存客户端 EnyimMemcachedCore 进行了高并发下的压力测试,发现在 linux 上高并发下使用 async 异步方法读取缓存数据会 ...