在实际项目开发中,定义全局异常处理至关重要通过全局异常处理器(使@controlleradvice和@exceptionhandler注解),可以集中捕获和处理各种异常,避免在每个控制器方法中重复编写异常处理代码。
住家饭系统将异常类型分为客户端异常(clientexception),系统异常(serviceexception),远程调用异常(remoteexception)。类结构图如下:

我们需先定义一个抽象异常类 abstractexception ,该抽象类继承自 runtimeexception 类,通过该类约束异常类行为。
/**
* 抽象项目中的三类异常,客户端异常、服务端异常和远程服务调用异常
*/
@data
public abstract class abstractexception extends runtimeexception{
public final string errorcode;
public final string errormsg;
public abstractexception(string errormsg, throwable throwable, ierrorcode errorcode) {
super(errormsg, throwable);
this.errorcode = errorcode.code();
this.errormsg = optional.ofnullable(stringutils.haslength(errormsg) ? errormsg : null).orelse(errorcode.msg());
}
}接着在分别定义客户端异常、服务端异常和远程调用异常类。
public class clientexception extends abstractexception{
public clientexception (ierrorcode errorcode) {
super(null, null, errorcode);
}
public clientexception(ierrorcode errorcode, string errormsg) {
super(errormsg, null, errorcode);
}
public clientexception(string message, throwable throwable, ierrorcode errorcode) {
super(message, throwable, errorcode);
}
@override
public string tostring() {
return "clientexception{" +
"code='" + errorcode + "'," +
"message='" + errormsg + "'" +
'}';
}
}public class serviceexception extends abstractexception{
public serviceexception(string message) {
this(message, null, baseerrorcode.service_error);
}
public serviceexception(ierrorcode errorcode) {
this(null, errorcode);
}
public serviceexception(string message, ierrorcode errorcode) {
this(message, null, errorcode);
}
public serviceexception(string message, throwable throwable, ierrorcode errorcode) {
super(optional.ofnullable(message).orelse(errorcode.msg()), throwable, errorcode);
}
@override
public string tostring() {
return "serviceexception{" +
"code='" + errorcode + "'," +
"message='" + errormsg + "'" +
'}';
}
}public class remoteexception extends abstractexception{
public remoteexception(string errormsg, throwable throwable, ierrorcode errorcode) {
super(errormsg, throwable, errorcode);
}
@override
public string tostring() {
return "remoteexception{" +
"code='" + errorcode + "'," +
"message='" + errormsg + "'" +
'}';
}
}这样,我们就完成了对三大基本异常类的定义。接下来我们需要通过springboot提供的@controlleradvice和@exceptionhandler注解来实现全局异常拦截并处理。我们需定义一个globalexceptionhandler类,在该类中分别对参数验证异常、应用内抛出的异常和最顶级的throwable异常进行处理。
component("globalexceptionhandlerbyadmin")
@slf4j
@restcontrolleradvice
public class globalexceptionhandler {
/**
* 拦截参数验证异常
*/
@sneakythrows
@exceptionhandler(value = methodargumentnotvalidexception.class)
public result validexceptionhandler(httpservletrequest request, methodargumentnotvalidexception ex) {
bindingresult bindingresult = ex.getbindingresult();
fielderror firstfielderror = collectionutil.getfirst(bindingresult.getfielderrors());
string exceptionstr = optional.ofnullable(firstfielderror)
.map(fielderror::getdefaultmessage)
.orelse(strutil.empty);
log.error("[{}] {} [ex] {}", request.getmethod(), geturl(request), exceptionstr);
return results.failure(baseerrorcode.client_error.code(), exceptionstr);
}
/**
* 拦截应用内抛出的异常
*/
@exceptionhandler(value = {abstractexception.class})
public result abstractexception(httpservletrequest request, abstractexception ex) {
if (ex.getcause() != null) {
log.error("[{}] {} [ex] {}", request.getmethod(), request.getrequesturl().tostring(), ex.tostring(), ex.getcause());
return results.failure(ex);
}
log.error("[{}] {} [ex] {}", request.getmethod(), request.getrequesturl().tostring(), ex.tostring());
return results.failure(ex);
}
/**
* 拦截未捕获异常
*/
@exceptionhandler(value = throwable.class)
public result defaulterrorhandler(httpservletrequest request, throwable throwable) {
log.error("[{}] {} ", request.getmethod(), geturl(request), throwable);
if (objects.equals(throwable.getclass().getsuperclass().getsimplename(), abstractexception.class.getsimplename())) {
string errorcode = reflectutil.getfieldvalue(throwable, "errorcode").tostring();
string errormessage = reflectutil.getfieldvalue(throwable, "errormessage").tostring();
return results.failure(errorcode, errormessage);
}
return results.failure();
}
private string geturl(httpservletrequest request) {
if (stringutils.isempty(request.getquerystring())) {
return request.getrequesturl().tostring();
}
return request.getrequesturl().tostring() + "?" + request.getquerystring();
}
}今后,我们在项目里抛出的所有异常,都可以被 globalexceptionhandler 类捕获并进行相应的处理。
public void register(userregisterreqdto requestparam) {
if(objectutils.isempty(requestparam)) throw new clientexception(client_error);
if (hasusername(requestparam.getusername())) {
throw new serviceexception(user_name_exist);
}
try {
int inserted = basemapper.insert(beanutil.tobean(requestparam, userdao.class));
if (inserted <= 0) {
throw new clientexception(user_save_error);
}
} catch (duplicatekeyexception ex) {
throw new serviceexception(user_exist);
}
}到此这篇关于springboot实现全局异常处理的文章就介绍到这了,更多相关springboot全局异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论