1.Restful接口:当出现异常的时候,我们并不希望前端能够看到后台异常栈信息,更希望正常返回一段JSON,效果如下:
有两种方案,一种是intercept的形式,但如果用来处理异常的话,貌似不太适合,并非所有请求都会出现异常,我们更希望出现异常的时候再去处理。所以,不推荐intercept的形式。更推荐通过如下方式去处理:
@ControllerAdvice(basePackages = {"com.ripplechan.server.controller"})
public class ControllerException {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public Map<String,Object> exception(Exception e) {
HashMap<String, Object> map = new HashMap<>();
if (e instanceof BaseException) {
BaseException e1 = (BaseException) e;
map.put("message", e1.getMessage());
map.put("code", e1.getCode());
} else {
map.put("message", BaseException.DEFAULT_MESSAGE);
map.put("code", BaseException.DEFAULT_CODE);
}
return map;
}
}
2.普通异常,比如404之类的,直接在项目的resources目录下面建立如下结构
文件名和HttpStatus状态一致即可,然后我们就能看到如下效果:
有了上面的方案,我们的controller,再也不会出现下面这样的代码了: