欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot全局异常处理方式

程序员文章站 2022-03-18 22:59:58
目录springboot全局异常处理springboot全局异常处理——@controlleradvice+exceptionhandler一、全局捕获异常后,返回json给浏览器二、全局捕获异常后,...

springboot全局异常处理

为了让客户端能有一个更好的体验,当客户端发送请求到服务端发生错误时服务端应该明确告诉客户端错误信息。

SpringBoot全局异常处理方式

springboot内置的异常处理返回的界面太杂乱,不够友好。我们需要将异常信息做封装处理响应给前端。本文介绍的为将错误信息统一封装成如下格式json响应给前端。

{
	code:10001,
	message:xxxxx,
	request:get url
}

自定义异常类

package com.lin.missyou.exception;
public class httpexception extends runtimeexception{
    protected integer code;
    protected integer httpstatuscode;
    public integer getcode() {
        return code;
    }
    public void setcode(integer code) {
        this.code = code;
    }
    public integer gethttpstatuscode() {
        return httpstatuscode;
    }
    public void sethttpstatuscode(integer httpstatuscode) {
        this.httpstatuscode = httpstatuscode;
    }
}
package com.lin.missyou.exception;
public class notfoundexception extends httpexception{
    public notfoundexception(int code){
        this.httpstatuscode = 404;
        this.code = code;
    }
}
package com.lin.missyou.exception;
public class forbiddenexception extends httpexception{
    public forbiddenexception(int code){
        this.httpstatuscode = 403;
        this.code = code;
    }
}

创建一个用于封装异常信息的类unifyresponse

package com.lin.missyou.core;
public class unifyresponse {
    private int code;
    private string message;
    private string request;
    public int getcode() {
        return code;
    }
    public string getmessage() {
        return message;
    }
    public string getrequest() {
        return request;
    }
    public unifyresponse(int code, string message, string request) {
        this.code = code;
        this.message = message;
        this.request = request;
    }
}

将异常信息写在配置文件exception-code.properties里

lin.codes[10000] = 通用异常
lin.codes[10001] = 通用参数错误

自定义配置类管理配置文件

package com.lin.missyou.core.configuration;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.context.annotation.propertysource;
import org.springframework.stereotype.component;
import java.util.hashmap;
import java.util.map;
@propertysource(value="classpath:config/exception-code.properties")
@configurationproperties(prefix = "lin")
@component
public class exceptioncodeconfiguration {
    private map<integer,string> codes = new hashmap<>();
    public map<integer, string> getcodes() {
        return codes;
    }
    public void setcodes(map<integer, string> codes) {
        this.codes = codes;
    }
    public string getmessage(int code) {
        string message = codes.get(code);
        return message;
    }
}

创建一个全局异常处理类globalexceptionadvice,用@controlleradvice标明异常处理类。@responsestatus用于指定http状态码。

@exceptionhandler标明异常处理器,传入参数指定当前函数要处理哪种类型的异常。springboot会帮我们把这些异常信息传入到函数。第一个函数用于处理未知异常,不需要向前端提供详细的错误原因,只需提示统一的文本信息即可。

第二个函数用于处理已知异常,需要指明具体的错误原因,需要根据exception传递过来的信息灵活的定制httpstatuscode。responseentity可以自定义很多属性,包括可以设置httpheaders,httpbodys,httpstatus。

package com.lin.missyou.core;
import com.lin.missyou.core.config.exceptioncodeconfiguration;
import com.lin.missyou.exception.httpexception;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpheaders;
import org.springframework.http.httpstatus;
import org.springframework.http.mediatype;
import org.springframework.http.responseentity;
import org.springframework.validation.objecterror;
import org.springframework.web.bind.methodargumentnotvalidexception;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.bind.annotation.responsestatus;
import javax.servlet.http.httpservletrequest;
import javax.validation.constraintviolation;
import javax.validation.constraintviolationexception;
import java.util.list;
@controlleradvice
public class globalexceptionadvice {
    @autowired
    exceptioncodeconfiguration exceptioncodeconfiguration ;
    @exceptionhandler(exception.class)
    @responsebody
    @responsestatus(httpstatus.internal_server_error)
    public unifyresponse handleexception(httpservletrequest req,exception e){
        string method = req.getmethod();
        string requesturl = req.getrequesturi();
        system.out.println(e);
        unifyresponse unifyresponse = new unifyresponse(9999,"服务器错误",method+" "+requesturl);
        return unifyresponse;
    }
    @exceptionhandler(httpexception.class)
    public responseentity<unifyresponse> handlehttpexception(httpservletrequest req, httpexception e){
        string method = req.getmethod();
        string requesturl = req.getrequesturi();
        system.out.println(e);
        unifyresponse unifyresponse = new unifyresponse(e.getcode(),exceptioncodeconfiguration.getmessage(e.getcode()),method+" "+requesturl);
        httpheaders httpheaders = new httpheaders();
        httpheaders.setcontenttype(mediatype.application_json);
        httpstatus httpstatus = httpstatus.resolve(e.gethttpstatuscode());
        responseentity<unifyresponse> responseentity = new responseentity(unifyresponse,httpheaders,httpstatus);
        return responseentity;
    }
    //参数校验
    @exceptionhandler(methodargumentnotvalidexception.class)
    @responsebody
    @responsestatus(httpstatus.bad_request)
    public unifyresponse handlebeanvalidation(httpservletrequest req, methodargumentnotvalidexception e){
        string method = req.getmethod();
        string requesturl = req.getrequesturi();
        list<objecterror> errors = e.getbindingresult().getallerrors();
        string message = formatallerrormessages(errors);
        return new unifyresponse(10001,message,method+" "+requesturl);
    }
    private string formatallerrormessages(list<objecterror> errors){
        stringbuffer errormsg = new stringbuffer();
        errors.foreach(error ->
                errormsg.append(error.getdefaultmessage()).append(";")
        );
        return errormsg.tostring();
    }
    @exceptionhandler(constraintviolationexception.class)
    @responsebody
    @responsestatus(httpstatus.bad_request)
    public unifyresponse handleconstrainexception(httpservletrequest req, constraintviolationexception e){
        string method = req.getmethod();
        string requesturl = req.getrequesturi();
        string message = e.getmessage();
        return new unifyresponse(10001,message,method+" "+requesturl);
    }
}

SpringBoot全局异常处理方式

响应信息可能会出现乱码现象,修改配置文件编码。在设置面板搜索file encodings,default encoding for properties files选择utf-8,勾选transparent native-to-ascii conversion

SpringBoot全局异常处理方式

springboot全局异常处理——@controlleradvice+exceptionhandler

一、全局捕获异常后,返回json给浏览器

项目结构:

SpringBoot全局异常处理方式

1、自定义异常类 myexception.java

package com.gui.restful;
/**
 * 自定义异常类
 */
public class myexception extends runtimeexception{
    private string code;
    private string msg;
    public myexception(string code,string msg){
        this.code=code;
        this.msg=msg;
    }
    public string getcode() {
        return code;
    }
    public void setcode(string code) {
        this.code = code;
    }
    public string getmsg() {
        return msg;
    }
    public void setmsg(string msg) {
        this.msg = msg;
    }
}

2、控制器 mycontroller.java

package com.gui.restful;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.bind.annotation.restcontroller;
/**
 * controller抛出异常
 */
@restcontroller
public class mycontroller {
    @requestmapping("hello")
    public string hello() throws exception{
        throw new myexception("101","系统异常");
    }
}

3、全局异常处理类 mycontrolleradvice

package com.gui.restful;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.responsebody;
import java.util.hashmap;
import java.util.map;
/**
 * 全局异常捕获处理
 */
@controlleradvice //controller增强器
public class mycontrolleradvice {
    @responsebody
    @exceptionhandler(value=myexception.class) //处理的异常类型
    public map myexceptionhandler(myexception e){
        map<string,string> map=new hashmap<>();
        map.put("code",e.getcode());
        map.put("msg",e.getmsg());
        return map;
    }
}

4、运行结果

启动应用,访问 http://localhost:8080/hello,出现以下结果,说明自定义异常被成功拦截

SpringBoot全局异常处理方式

二、全局捕获异常后,返回页面给浏览器

1、自定义异常类 myexception.java(同上)

2、控制器 mycontroller.java(同上)

3、全局异常处理类 mycontrolleradvice

package com.gui.restful;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.servlet.modelandview;
import java.util.hashmap;
import java.util.map;
/**
 * 全局异常捕获处理
 */
@controlleradvice //controller增强器
public class mycontrolleradvice {
    @exceptionhandler(value=myexception.class) //处理的异常类型
    public modelandview myexceptionhandler(myexception e){
        modelandview modelandview=new modelandview();
        modelandview.setviewname("error");
        modelandview.addobject("code",e.getcode());
        modelandview.addobject("msg",e.getmsg());
        return modelandview;
    }
}

4、页面渲染 error.ftl(用freemarker渲染)

pom.xml中引入freemarker依赖

		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-freemarker</artifactid>
		</dependency>

error.ftl

<!doctype>
<html>
<head>
<title>错误页面</title>
</head>
<body>
<h1>code:$[code]</h1>
<h1>msg:${msg}</h1>
</body>
</html>

5、运行结果

启动应用,访问 http://localhost:8080/hello,出现以下结果,说明自定义异常被成功拦截

SpringBoot全局异常处理方式

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。