springboot 默认异常处理
SpringBoot默认有自定义异常处理的体系,在做SpringBoot项目的时候,如果是抛出了运行时异常,springBoot并会对异常进行处理,返回如下异常信息:
{
"timestamp": 1517294278132,
"status": 500,
"error": "Internal Server Error",
"exception": "com.lgy.common.exception.BusinessException",
"message": "[001]自定义的uncheck 异常!",
"path": "/validateExceptionTest"
}
追究其原因,发现SpirngBoot出现异常信息时候,会默认访问/error,springBoot种有BasicErrorController这个类来处理异常信息:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package org.springframework.boot.autoconfigure.web; import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorProperties.IncludeStacktrace;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties; public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
this(errorAttributes, errorProperties, Collections.emptyList());
} public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorViewResolvers);
Assert.notNull(errorProperties, "ErrorProperties must not be null");
this.errorProperties = errorProperties;
} public String getErrorPath() {
return this.errorProperties.getPath();
} @RequestMapping(
produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView == null?new ModelAndView("error", model):modelAndView;
} @RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = this.getStatus(request);
return new ResponseEntity(body, status);
} protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
IncludeStacktrace include = this.getErrorProperties().getIncludeStacktrace();
return include == IncludeStacktrace.ALWAYS?true:(include == IncludeStacktrace.ON_TRACE_PARAM?this.getTraceParameter(request):false);
} protected ErrorProperties getErrorProperties() {
return this.errorProperties;
}
}
如果要取代SpringBoot默认的异常处理信息方式,继承ErrorController:
package com.lgy.controller; import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import java.util.Map; /**
* Created by fengch on 2018/1/30.
*/
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class FundaErrorController implements ErrorController {
private static final String PATH = "/error"; @Autowired
private ErrorAttributes errorAttributes; @Override
public String getErrorPath() {
return PATH;
} @RequestMapping
@ResponseBody
public JSONObject doHandleError(HttpServletRequest request) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map<String,Object> errorAttributesData = errorAttributes.getErrorAttributes(requestAttributes,true);
Integer status=(Integer)errorAttributesData.get("status"); //状态码
String path=(String)errorAttributesData.get("path"); //请求路径
String messageFound=(String)errorAttributesData.get("message"); //异常信息 JSONObject reData = new JSONObject();
reData.put("status_", status);
reData.put("path_", path);
reData.put("message", messageFound);
return reData;
}
}
接着在访问,并是自定义处理的异常信息了:
{
"message": "[001]自定义的uncheck 异常!",
"path_": "/validateExceptionTest",
"status_": 500
}
【转载】
springboot 默认异常处理的更多相关文章
- java框架之SpringBoot(7)-异常处理
前言 在 SpringBoot 项目中,默认情况下,使用浏览器访问一个不存在的地址会返回如下错误页面: 而当客户端未非浏览器时,错误信息则会以 json 数据返回,如下: 会出现如上效果的原因是 Sp ...
- springboot 全局异常处理
springboot 全局异常处理 研究了半天springboot的全局异常处理,虽然还是需要再多整理一下,但是对于常见的404和500足以可以区分开,能够根据这两个异常分别处理 首先配置视图解析路径 ...
- Springboot的异常处理与自定义异常
园友们好,元旦很快就到来了,提前祝各位园友们元旦快乐,今天给大家分享一个工作中必用一个知识点,就是使用枚举构建自定义异常并应用于springboot的异常处理器.开始之前我先把这个案例的结构大致说明一 ...
- springboot默认创建的bean是单实还是多例
转:https://blog.csdn.net/q1512451239/article/details/53122687 springboot默认创建的bean是单实还是多例 曾经面试的时候有面试官问 ...
- spring 或 springboot统一异常处理
spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义 ...
- 配置和修改springboot默认国际化文件
SpringBoot默认国际化文件为:classpath:message.properties,如果放在其它文件夹中,则需要在application.properties配置属性spring.mess ...
- Springboot默认加载application.yml原理以及扩展
Springboot默认加载application.yml原理以及扩展 SpringApplication.run(...)默认会加载classpath下的application.yml或applic ...
- 将SpringBoot默认使用的tomcat替换为undertow
随着微服务的兴起,越来越多的互联网应用在选择web容器时使用更加轻量的undertow或者jetty.SpringBoot默认使用的容器是tomcat,如果想换成undertow容器,只需修改pom. ...
- SpringBoot默认日志的使用方法及常用配置
SpringBoot默认采用slf4j+logback 的组合形式,但也提供对JUL.log4j2.Logback提供了默认配置. 我们使用IDEA的spring初始化创建一个springboot项目 ...
随机推荐
- 安利一款强大的学习软件XMind(顺便放上这几天制作的JavaSE的思维导图day1-day4)
最近在学习Java,并且在使用一款非常酷炫无敌吊炸天的软件,思维导图制作神器-XMind,然后就像分享给大家,至于XMind是什么大家自行百度,在这里我就不赘述了 我这里说下我认为的好的实用的常用快捷 ...
- echart的x轴换行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 软件综合实践Axure介绍
首先就是下载安装Axure这款软件了,在百度上搜索“”Axure rp下载“”即可,下载完成后,打开exe安装,根据步骤一步步点击下一步即可完成安装. 运行该软件时会出现类似于填写激活码的东西,这时依 ...
- PAT (Advanced Level) Practice 1001 A+B Format (20 分)
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400 Calculate a+b and ...
- [转载]URI 源码分析
需要提前了解下什么是URI,及URI和URL的区别: URI. URL 和 URN 的区别 URI 引用包括最多三个部分:模式.模式特定部分和片段标识符.一般为: 模式:模式特定部分:片段 如果省略模 ...
- [转载]Oracle用户创建及权限设置
出处:https://www.cnblogs.com/buxingzhelyd/p/7865194.html 权限: create session 允许用户登录数据库权限 create table ...
- 解决 flannel.1 interface state DOWN
ip a 查看结果 flannel.1 i state UNKNOWN 并且五 inet 发现日志 device (flannel.1): state change: unmanaged -> ...
- C# 解析html中筛选class的问题
C# 解析html中筛选class的问题 C# html解析 class 类 当我们用C#的.net解析html的时候,当html的元素没有id,并且没有过多的属性供筛选,只能通过class=&qu ...
- day 07
# 数据类型的相互转化# 字符编码# 文件操作 # 1.哪些类型可以转化为数字# res = int('10')# print(res)# res = int('-3')# print(res)# r ...
- nodeEE双写与分布式事务要点一二
数据库与缓存双写问题 计算机领域任何一个问题都可以通过增加一个抽象"层"来解决. 业务中为了减少热点数据不必要的db查询,往往会增加一层缓存来解决I/O性能.可是I/O多了一层也就 ...