使用场景
当使用Spring MVC进行Web开发的时候,对于异常可以进行集中式的处理
首先声明一个异常枚举类
public enum ExceptionDesception {
NO_PERMISSION(-1,"无权限");
private int code;
private String msg;
ExceptionDesception(int code,String msg){
this.code=code;
this.msg=msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
方式1,使用继承或者实现接口的方式
a.声明一个BaseController用来集中处理异常
public class BaseController {
@ExceptionHandler({WebApiException.class})
@ResponseBody
public Object expHandler(WebApiException e){
return createResult(e);
}
public JSONObject createResult(BaseException e){
JSONObject result=new JSONObject();
result.put("code",e.getCode());
result.put("msg",e.getMessage());
return result;
}
}
或者上将其声明为接口,同时方法使用 default修饰然后让Controller继承自该BaseController即可
方式2 使用 @ControllerAdvice 该注解来处理异常
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler({WebApiException.class})
@ResponseBody
public Object expHandler(WebApiException e){
return createResult(e);
}
public JSONObject createResult(BaseException e){
JSONObject result=new JSONObject();
result.put("code",e.getCode());
result.put("msg",e.getMessage());
return result;
}
}
通过方式2,controller并不需要实现或者继承就能做到异常处理,相对方式1更加解耦一些