springboot 默认异常处理

摘要:
////IntelliJIDEA//(由Fernflower反编译器驱动)//packageorg.springframework.boot.autoconfigure.web;importorg.springframework.util.Assert;

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 默认异常处理》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vue实现消息的无缝滚动效果C#中IntPtr下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

再来说说LumaQQ.NET怎么发群消息

        QQ群有两个ID,内部ID和外部ID。外部ID就是我们平时常见的ID,搜索啊,查看啊,都是这个ID。         而内部ID就不常见了,应该说用QQ的人是从来不知道还有这个ID的。但是,这个ID是这篇文章的重点。因为发群信息必须用到这个ID。         用过LumaQQ.NET的人,尝试过用QQ上可见的群号码发群消息,相信都是超...

httprunner(setup和teardown及hook)

httprunner有两种setup和teardown的定义方式,一个是测试类级别,一个是测试步骤级别的定义。 测试类级别的setup和teardown第一种写法setup和teardown: #!/user/bin/env python # -*- coding: utf-8 -*- """ ----------------------...

记一次gitlab-ce数据恢复过程

使用的gitlab是用docker启动的,数据目录的owner/group信息被意外全部更改成了root:root导致服务不可用。最终通过复原文件所有者的方式恢复了服务。 步骤如下:   1. 打包备份gitlab所有的数据目录(我们的是/data/gitlab/data;/data/gitlab/config;/data/gitlab/logs),并清空...

数字签名

首先介绍一下散列算法,这种算法在计算机科学当中相当常见,它接收一大块的数据并将其压缩成最初数据的一个指纹或者摘要。 举个例子,18/2=9,在某种程度上9就是表达式(18/2)的指纹(也可以叫摘要)。这时我们无论计算机多少次,结果都会是9。这时无论我们对18进行多么细微的改动,其运算结果都会改变。返过来我们把计算结果9告诉你,不告诉你任何进一步的信息,你就...

用configmap管理配置

一、ConfigMap介绍管理配置: ConfigMap介绍 Secret 可以为 Pod 提供密码、Token、私钥等敏感数据;对于一些非敏感数据,比如应用的配置信息,则可以用 ConfigMap ConfigMap 的创建和使用方式与 Secret 非常类似,主要的不同是数据以明文的形式存放。 与 Secret 一样,ConfigMap 也支持四种创...

使用VsCode的Rest Client进行请求测试

平时工作使用VSCode进行request的提交和测试 =>{按照Rest Client 可以很轻松的帮助我们完成代码的调试,而且能帮我们编译成各种语言的代码使用(Generate Code Snippet)} 如下表:我是用了Get请求,然后Shift+Ctrl+P进入VsCode的命令行,然后选择 Rest Client:Generate Cod...