在项目运行过程当中,是否是各类异常,若是咱们每一个都须要用 try{}catch(Exception e){} 的话,那么就会写特别特别多的重复代码,就会显得很是low,因此Spring为咱们提供了全局异常处理机制,咱们只须要往外抛异常就能够了:java
1: 自定义异常类(没有不影响,只演示一下)git
package com.gy.demo.common.handler; /** * Description: 参数异常类 * * @author geYang * @since 2017/12/28 **/ public class ParamException extends RuntimeException { private int code; public ParamException(ResultEnum resultEnum){ super(resultEnum.getMessage()); this.code = resultEnum.getCode(); } public int getCode () { return code; } public void setCode (int code) { this.code = code; } }
2: 自定义返回状态枚举web
package com.gy.demo.common.handler; /** * Description: 返回结果状态码 * * @author geYang * @since 2017/12/28 **/ public enum ResultEnum { PARAM_NULL(401,"参数为空"), PARAM_ERROR(402,"参数异常"), SUCCESS(200,"SUCCESS"), RETURN_NULL(201,"返回值为空"), ; private int code; private String message; ResultEnum (int code, String message) { this.code = code; this.message = message; } public int getCode () { return this.code; } public String getMessage () { return this.message; } }
3: 自定义返回状态类:spring
package com.gy.demo.common.handler; import org.springframework.http.HttpStatus; import java.util.HashMap; /** * Description: 请求返回状态类 * * @author geYang * @since 2017/12/18 **/ public class R extends HashMap<String, Object> { public R() { put("code", HttpStatus.OK.value()); } public R (ParamException paramException) { put("code", paramException.getCode()); put("msg", paramException.getMessage()); } public static R error () { return error( HttpStatus.INTERNAL_SERVER_ERROR.value(), "未知异常,请联系管理员"); } public static R error (String msg) { return error(HttpStatus.INTERNAL_SERVER_ERROR.value(),msg); } public static R error(int code, String msg) { R r = new R(); r.put("code", code); r.put("msg", msg); return r; } public static R ok(Object data) { R r = new R(); r.put("data", data); return r; } }
4: 异常处理类app
package com.gy.demo.common.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * Description: 全局异常处理类 * * @author geYang * @since 2017/12/28 **/ @ControllerAdvice public class ExceptHandler { private Logger logger = LoggerFactory.getLogger(ExceptHandler.class); @ResponseBody @ExceptionHandler(value = Exception.class) public R doExceptHandler(Exception e){ /* 判断异常是否为自定义异常 */ if(e instanceof ParamException){ ParamException p = (ParamException) e; return R.error(p.getCode(),p.getMessage()); } else { logger.error("系统异常",e); return R.error(e.getMessage()); } } }
5: 测试:ide
@GetMapping("/test/{id}") public Object test(Integer id) throws Exception{ if(id<5){ throw new ParamException(ResultEnum.PARAM_ERROR); } else if (id<10) { } return R.ok(null); }
参考大神: https://www.imooc.com/video/14341测试
项目源码: https://gitee.com/ge.yang/SpringBootthis