一、返回信息结果封装
- 前后端分离的基本接口返回封装,
code默认200
,异常就设置SC_INTERNAL_SERVER_ERROR
即500
(因为是前端整权限) - 最后判断结果
judgeResult
,写操作
都是返回数字都懂
public class HttpResult {
private int code = 200;
private String msg;
private Object data;
//getter、setter省略
public static HttpResult error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
}
public static HttpResult error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static HttpResult error(String scInternalServerError, String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static HttpResult error(int code, String msg) {
HttpResult result = new HttpResult();
result.setCode(code);
result.setMsg(msg);
return result;
}
public static HttpResult error(String msg, Object data) {
HttpResult result = new HttpResult();
result.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
result.setMsg(msg);
result.setData(data);
return result;
}
public static HttpResult ok(String msg) {
HttpResult result = new HttpResult();
result.setMsg(msg);
return result;
}
public static HttpResult ok(Object data) {
HttpResult result = new HttpResult();
result.setData(data);
return result;
}
public static HttpResult ok(String msg, Object data) {
HttpResult result = new HttpResult();
result.setMsg(msg);
result.setData(data);
return result;
}
public static HttpResult ok() {
return new HttpResult();
}
public static HttpResult judgeResult(Object o) {
Integer judge = 0;
if (ObjectUtils.anyNull(o)) {
judge = 0;
} else if (o instanceof Integer) {
judge = (Integer) o;
}
return judge > 0 ? ok("操作成功", judge) : error("操作失败", judge);
}
}
二、统一异常处理
- 定义
GlobalExceptionHandler
,标注@RestControllerAdvice
(与@ControllerAdvice
类似,差别如@RestController和@Controller
) @ControllerAdvice
:
@ControllerAdvice
是一个@Component
,用于定义@ExceptionHandler
,@InitBinder和@ModelAttribute
方法,适用于所有使用@RequestMapping
方法。
一般就使用@ExceptionHandler
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ApplicationRunException.class)
public HttpResult baseException(ApplicationRunException e) {
return HttpResult.error(e.getMessage());
}
}
- 这里处理自定义的异常信息封装
ApplicationRunException
(继承自RuntimeException
) - 继承
RuntimeException与Exception差别
:
继承
RuntimeException
,
1、当我们捕获ApplicationRunException
异常时,不用在方法外额外的throws
2、捕获的方法被注解时,RuntimeException
不会报错,·Exception·会报错
ApplicationRunException
的用途:即throw new ApplicationRunException ()
时,给的参数将被我们作为msg
返回
public class ApplicationRunException extends RuntimeException {
private String code;
private String message;
private Exception e;
// 看了上面的用途,可以知道我们只要定义简单的getter方法(省略)
//和一些有、无参构造
public ApplicationRunException() {
this.code = null;
this.message = null;
this.e = null;
}
public ApplicationRunException(String message) {
this.message = message;
}
}
- 自定义异常方法处理使用:
只需要在实现方法中
throw new ApplicationRunException ()
,
这一步会帮我们,直接拦截下正确的返回,转而走GlobalExceptionHandler
中的baseException
返回HttpResult.error(e.getMessage());
(这样我们的控制器只需要用到HttpResult.ok()
)
然后在controller
控制器返回我们的HttpResult
即可
那么,就到这里
\(^o^)/~