springMVC统一处理异常信息

来源:互联网 发布:淘宝达人链接怎么获取 编辑:程序博客网 时间:2024/05/29 02:32
springMVC统一处理异常信息


通过抛出异常,返回json提示信息。
1.在项目中模拟一个异常。

try {int i=1/0;} catch (Exception e){//自定义异常,存储提示信息,防止错误信息丢失throw new CustomException("除数不能为零",e);}
2.自定义异常。
public class CustomException extends RuntimeException {public CustomException(String message, Throwable cause) {super(message, cause);}public CustomException() {}}

3.在spring能扫描到的包内,(可以对全部的controller进行CustomException异常捕获)
@ControllerAdvicepublic class RunTime {@ExceptionHandler(CustomException.class)public @ResponseBody Map<String,Object> demo(NativeWebRequest request, CustomException e){Map<String,Object> map=new HashMap<String,Object>();map.put("resCode", 1);map.put("msg", e.getMessage());//记录日志--- 略return map; }}
 或者:在controller中:(只能捕获本controller中的CustomException异常信息)
@ExceptionHandler(CustomException.class)public @ResponseBody Map<String,Object> demo(NativeWebRequest request, CustomException e){Map<String,Object> map=new HashMap<String,Object>();map.put("resCode", 1);map.put("msg", e.getMessage());return map;}

4.返回信息:
{  "resCode": 1,  "msg": "除数不能为零"}











0 0
原创粉丝点击