Spring Boot学习入门之统一异常处理详解
前言
关于之前的一篇所讲到的表单验证中提到,如果产生错误,可以得到错误的信息,但是返回值的问题却没有考虑。
其中所提到的Controller:
@RequestMapping(value="/doRegister",method=RequestMethod.POST)
public@ResponseBodyUserdoRegister(@ValidUseruser,BindingResultresult,Modelmodel){
if(result.hasErrors()){
Listlist=result.getAllErrors();
for(ObjectErrorerror:list){
System.out.println(error.getDefaultMessage());
}
returnnull;
}
System.out.println("注册..");
returnuser;
}
如果验证不通过,我们不应该返回null的,这会对前端来说并不友好。
所以我们应该定义一个统一的返回格式:
publicclassReturnType{
privateintcode;
privateUserdata;
privateStringmsg;
publicReturnType(intcode,Stringmsg,Userdata){
this.code=code;
this.msg=msg;
this.data=data;
}
publicintgetCode(){
returncode;
}
publicvoidsetCode(intcode){
this.code=code;
}
publicUsergetData(){
returndata;
}
publicvoidsetData(Userdata){
this.data=data;
}
publicStringgetMsg(){
returnmsg;
}
publicvoidsetMsg(Stringmsg){
this.msg=msg;
}
}
这样一来,返回的结果中的json的格式是固定的。
虽然我们的希望是好的,但是并不是总是可以这样的,因为不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。
如果存在下面这种情况:
@RequestMapping(value="/doRegister",method=RequestMethod.POST)
public@ResponseBodyReturnTypedoRegister(@ValidUseruser,BindingResultresult,Modelmodel)throwsException{
thrownewException("newException");
}
这就好像在调用Service层代码的时候,执行方法的过程中遇到了一个异常,那么回得到什么样的结果呢?
无论如何,返回的肯定不是我们之前定义好的格式的返回值。
那我们应该怎么做呢?
这里就需要进行统一的异常处理了。
@ControllerAdvice
publicclassExceptionHandle{
/*表明这个handler只处理什么类型的异常
**/
@ExceptionHandler(value=Exception.class)
//返回值为json或者其他对象
@ResponseBody
publicReturnTypehandle(Exceptione){
returnnewReturnType(-1,e.getMessage(),null);
}
}
创建这么一个handler类,当Controller抛出异常的时候,就会委托给这个类其中的方法进行执行。
这样一来,就不会出现即使抛出异常,也不会得到不是我们期望的返回值的结果了。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。