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项目 ...
随机推荐
- MQ知识点汇总
1. MQ是什么 2. MQ能做什么 3. 消息模式 4. 使用MQ的时候需要注意什么 5. 常用MQ 6. MQ的不足 7. 什么时候不适用MQ 8. MQ的组成 9. MQ的关注点 1. MQ是什 ...
- oracle 两张关联表执行更新update
UPDATE T_ASN_DTL ad1 SET ad1.cf03=( SELECT ac.TH003 FROM "T_ASN_DTL_copy" ac WHERE ac.udf0 ...
- mySQL简单操作(三)
1.事务 (1)ACID 原子性(不可分割性)automicity 一致性 consistency 隔离性 isolation 持久性 durability (2)事务控制语句 begin/start ...
- 火狐开发----如何快速的安装火狐XPI文件
第一步:火狐的自动安装扩展程序,https://addons.mozilla.org/zh-CN/firefox/addon/autoinstaller/ 第二步:安装wget工具,这个Linux应该 ...
- java0425 wen IO
- C语言实例:类型转换
数组转换成16进制数: #include <stdio.h> #include <stdlib.h> typedef unsigned char UINT8; typedef ...
- zeros()和ones()和eye()
python--zeros函数和ones函数 使用numpy.zeros,numpy.ones,numpy.eye等方法可以构造特定的矩阵 >>>from numpy import ...
- allure --version 异常io.airlift.airline.ParseArgumentsUnexpectedException: Found unexpected parameter
执行allure --version时,有时会出现如下异常: io.airlift.airline.ParseArgumentsUnexpectedException: Found unexpecte ...
- MySQL安装时MySQL server一直安装失败日志显示This application requires Visual Studio 2013 Redistributable
使用MySQL社区版的msi包进行安装,试了好多次,别的组件都能正常安装,只有MySQL server的安装状态显示为fail.删除所有安装的程序,包括所依赖的各种Microsoft发布的包,删除所有 ...
- 关于截取URL地址参数的方法
JS获取URL中最后一个斜杠前面的内容 var url = window.location.href; var index = url.lastIndexOf("\/"); str ...