您的位置:首页 > 编程语言 > Java开发

springboot rest controller 统一异常处理,ajax 形式

2018-08-16 11:42 851 查看

1. 建立 json 结果类,用于统一显示 json 结果

[code]public class JsonResult<T> {
// code=0表示成功,返回数据data。data!=0,表示错误,返回错误信息msg
private int code;
// 若有错误,data不生成json
@JsonInclude(JsonInclude.Include.NON_NULL)
private T data;
// 若无错误,msg 不生成 json
@JsonInclude(JsonInclude.Include.NON_NULL)
private String msg;

public JsonResult() {
code = 0;
}
public JsonResult<T> ok(T data) {
this.code = 0;
this.data = data;
return this;
}
public JsonResult<T> error(int code, String msg) {
this.code = code;
this.msg = msg;
return this;
}
// getter and setter
}

2. 建立自定义异常类,用于显示自定义的异常

[code]public class CustemerException extends Exception {
public CustemerException(String message) {
super(message);
}
}

3. 建立 rest controller 的异常抓捕类

[code]@RestControllerAdvice
public class JsonExceptionHandler {
@ExceptionHandler(value = Exception.class)
public JsonResult<String> resolveException(HttpServletRequest request, HttpServletResponse response, Exception e) {
JsonResult<String> result = new JsonResult<>();
return result.error(1, e.getMessage());
}
}

4. 在 rest controller的方法中抛出异常

[code]@RestController
public class TestController {
@RequestMapping("/test_error")
public Object testError() throws Exception {
if (true) {
throw new CustemerException("抛出自定义异常");
}
return 1;
}
}

5. 测试,运行项目,打开浏览器输入url


参考:http://www.fengyunxiao.cn

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐