本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一.用处:
当前端访问接口时,后端在抛出异常返回时,一般http的状态码为500,而前端的理想接收数据为:http状态码为200,表示请求成功,而异常返回的数据应该例为:code:400,message:找不到资源。
在controller层抛出异常时,异常处理器可以进行捕获然后根据自己的设定进行返回
二.优点:
1.对不同业务异常进行多样化处理(状态码设置,异常信息封装)
2.可以对服务器原来的异常封装(空指针异常、服务器异常等等)
三.实现:
1.自定义一个异常类:
public class CrePipServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final String ID_ERROR = "token异常:";
private String errCode;
private String errMessage;
public CrePipServiceException(String errCode, String errMessage) {
super(errMessage);
this.errCode = errCode;
this.errMessage = errMessage;
}
public static CrePipServiceException notEmpty(String name) {
return new CrePipServiceException("1000102",NOT_NULL + name);
}
}
2.定义异常处理器
@ControllerAdvice
public class PipeGlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(PipeGlobalExceptionHandler.class);
/**
* 处理自定义的业务异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = CrePipServiceException.class)
@ResponseBody
public ResultBody pipeExceptionHandler(HttpServletRequest req, CrePipServiceException e){
logger.error("发生业务异常!原因是:{}",e.getErrMessage());
return ResultBody.error(e.getErrCode(),e.getErrMessage());
}
}
3.在controller层抛出异常
@GetMapping("/getComponents")
public RestResponse<List> getComponentsList(@RequestParam String namespace, @RequestParam String component) {
if (namespace == null || "".equals(namespace)) {
throw CrePipServiceException.notEmpty("namespace");
}
if (component == null || "".equals(component)) {
throw CrePipServiceException.notEmpty("component");
}
List result = this.componentService.getProjectComponent(namespace, component);
return RestResponse.<List>builder().data(result).build();
}
4.查看返回信息编辑
四.遇到的问题:
1.@ControllerAdvice注解不生效
状态码一直不对,返回信息也不对,最开始以为是全局变量不对,后来又以为是异常类没定义好,胡整一通,都没用,后来查了一下博客,有人说是spring没扫描到,需要加@SpringBootApplication(scanBasePackages = {"com.test.admin","com.test.admin.exception"}
编辑
但是还是没生效,后来才发现我的全局异常处理类名字为GlobalExceptionHandler,可能被覆盖了,于是改成了PipGlobalExceptionHandler名,结果就好了 (😂,浪费了一整天时间在这上面~~~~~)
2.异常信息一直为null
由于自定义的异常类继承的RuntimeException,所以自定义的异常类构造方法需要super(errMessage)
编辑