返回异常
后台异常报错时往往让页面十分难堪,前端人员也看不懂报错信息。
此时需要一个json的封装类来封装需要返回的信息
数据封装
json封装数据往往有三个参数:msg、code、data。
报错时返回一个封装类,提前设置好msg和code返回给前端,方便前端人员观察。
@Data
public class JsonResult<T> {
private T data;
private String code;
private String msg;
/**
* 若没有数据返回,默认状态码为0,提示信息为:操作成功!
*/
public JsonResult() {
this.code = "0";
this.msg = "操作成功!";
}
/**
* 若没有数据返回,可以人为指定状态码和提示信息
* @param code
* @param msg
*/
public JsonResult(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
编写ExceptionHandler类
提前写好一个ExceptionHandler类,对可能出现的异常进行数据封装
@ControllerAdvice
@ResponseBody
public class GlovalExceptionHandler {
//打印log
private static final Logger logger = LoggerFactory.getLogger(GlovalExceptionHandler.class);
/**
* 缺少请求参数异常
* @param ex HttpMessageNotReadableException
* @return
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public JsonResult handleHttpMessageNotReadableException(
MissingServletRequestParameterException ex){
logger.error("缺少请求参数,{}", ex.getMessage());
return new JsonResult("400","缺少请求参数");
}
/**
* 空指针异常
* @param ex NullPointerException
* @return
*/
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public JsonResult handleTypeMismatchException(NullPointerException ex) {
logger.error("空指针异常,{}", ex.getMessage());
return new JsonResult("500", "空指针异常了");
}
/**
* 系统异常 预期以外异常
* @param ex
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public JsonResult handleUnexpectedServer(Exception ex) {
logger.error("系统异常:", ex);
return new JsonResult("500", "系统发生异常,请联系管理员");
}
}
编写controller测试类
编写一个controller类,使用post提交。
@RestController
@RequestMapping("/exception")
public class ExceptionController {
private static final Logger logger = LoggerFactory.getLogger(GlovalExceptionHandler.class);
@PostMapping("/test")
public JsonResult test(@RequestParam String name, @RequestParam String pass){
logger.info("name:{}",name);
logger.info("pass:{}",pass);
return new JsonResult();
}
}
测试异常
测试参数缺失的异常需要使用postman进行提交。
成功返回所需的json对象