正文
{
"success": true,
"code": 20000,
"message": "查询用户列表",
"data": {
"itms": [
{
"id": "1",
"username": "admin",
"role": "ADMIN",
"deleted": false,
"gmtCreate": "2019-12-26T15:32:29",
"gmtModified": "2019-12-26T15:41:40"
},{
"id": "2",
"username": "zhangsan",
"role": "USER",
"deleted": false,
"gmtCreate": "2019-12-26T15:32:29",
"gmtModified": "2019-12-26T15:41:40"
}
]
}
}
统一结果类的使用参考了mybatis-plus中R对象的设计。
最新面试题整理好了
统一异常处理
使用统一返回结果时,还有一种情况,就是程序的保存是由于运行时异常导致的结果,有些异常我们可以无法提前预知,不能正常走到我们return的R对象返回。
因此,我们需要定义一个统一的全局异常来捕获这些信息,并作为一种结果返回控制层
@ControllerAdvice
该注解为统一异常处理的核心
是一种作用于控制层的切面通知(Advice),该注解能够将通用的@ExceptionHandler、@InitBinder和@ModelAttributes方法收集到一个类型,并应用到所有控制器上
该类中的设计思路:
-
使用@ExceptionHandler注解捕获指定或自定义的异常;
-
使用@ControllerAdvice集成@ExceptionHandler的方法到一个类中;
-
必须定义一个通用的异常捕获方法,便于捕获未定义的异常信息;
-
-
自定义全局异常类
@Data
public class CMSException extends RuntimeException {
private Integer code;
public CMSException(Integer code, String message) {
super(message);
this.code = code;
}
public CMSException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
}
@Override
public String toString() {
return "CMSException{" + "code=" + code + ", message=" + this.getMessage() + '}';
}
}
统一异常处理器
// ...
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
/**-------- 通用异常处理方法 --------**/
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e) {
e.printStackTrace();
return R.error(); // 通用异常结果
}
/**-------- 指定异常处理方法 --------**/
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public R error(NullPointerException e) {
e.printStackTrace();
return R.setResult(ResultCodeEnum.NULL_POINT);
}
@ExceptionHandler(HttpClientErrorException.class)
@ResponseBody
public R error(IndexOutOfBoundsException e) {
e.printStackTrace();
return R.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
}
/**-------- 自定义定异常处理方法 --------**/
@ExceptionHandler(CMSException.class)
@ResponseBody
public R error(CMSException e) {
e.printStackTrace();
return R.error().message(e.getMessage()).code(e.getCode());
}
}
控制层展示
以下为展示当遇到null指定异常时,返回的结果信息
{