spring boot 全局异常处理及自定义异常类

全局异常处理:

定义一个处理类,使用@ControllerAdvice注解。

@ControllerAdvice注解:控制器增强,一个被@Component注册的组件。

配合@ExceptionHandler来增强所有的@requestMapping方法。

例如:@ExceptionHandler(Exception.class)  用来捕获@requestMapping的方法中所有抛出的exception。

代码:

  1. @ControllerAdvice
  2. public class GlobalDefultExceptionHandler {
  3. //声明要捕获的异常
  4. @ExceptionHandler(Exception.class)
  5. @ResponseBody
  6. public String defultExcepitonHandler(HttpServletRequest request,Exception e) {
  7.      return “error”;
  8. }
  9. }

这样,全局异常处理类完毕。可以添加自己的逻辑。


然后还有一个问题,有的时候,我们需要业务逻辑时抛出自定义异常,这个时候需要自定义业务异常类。

定义class:BusinessException ,使他继承于RuntimeException.

扫描二维码关注公众号,回复: 2035346 查看本文章

说明:因为某些业务需要进行业务回滚。但spring的事务只针对RuntimeException的进行回滚操作。所以需要回滚就要继承RuntimeException。

  1. public class BusinessException extends RuntimeException{
  2. }

然后,现在来稍微完善一下这个类。

当我们抛出一个业务异常,一般需要错误码和错误信息。有助于我们来定位问题。

所以如下:

  1. public class BusinessException extends RuntimeException{
  2. //自定义错误码
  3. private Integer code;
  4. //自定义构造器,只保留一个,让其必须输入错误码及内容
  5. public BusinessException(int code,String msg) {
  6. super(msg);
  7. this.code = code;
  8. }
  9. public Integer getCode() {
  10. return code;
  11. }
  12. public void setCode(Integer code) {
  13. this.code = code;
  14. }
  15. }

这时候,我们发现还有一个问题,如果这样写,在代码多起来以后,很难管理这些业务异常和错误码之间的匹配。所以在优化一下。

把错误码及错误信息,组装起来统一管理。

定义一个业务异常的枚举。

  1. public enum ResultEnum {
  2. UNKONW_ERROR(- 1, "未知错误"),
  3. SUCCESS( 0, "成功"),
  4. ERROR( 1, "失败"),
  5. ;
  6. private Integer code;
  7. private String msg;
  8. ResultEnum(Integer code,String msg) {
  9. this.code = code;
  10. this.msg = msg;
  11. }
  12. public Integer getCode() {
  13. return code;
  14. }
  15. public String getMsg() {
  16. return msg;
  17. }
  18. }

这个时候,业务异常类:

  1. public class BusinessException extends RuntimeException{
  2. private static final long serialVersionUID = 1L;
  3. private Integer code; //错误码
  4. public BusinessException() {}
  5. public BusinessException(ResultEnum resultEnum) {
  6. super(resultEnum.getMsg());
  7. this.code = resultEnum.getCode();
  8. }
  9. public Integer getCode() {
  10. return code;
  11. }
  12. public void setCode(Integer code) {
  13. this.code = code;
  14. }
  15. }

然后再修改一下全局异常处理类:

  1. @ControllerAdvice
  2. public class GlobalDefultExceptionHandler {
  3. //声明要捕获的异常
  4. @ExceptionHandler(Exception.class)
  5. @ResponseBody
  6. public <T> Result<?> defultExcepitonHandler(HttpServletRequest request,Exception e) {
  7. e.printStackTrace();
  8. if(e instanceof BusinessException) {
  9. Log.error( this.getClass(), "业务异常:"+e.getMessage());
  10. BusinessException businessException = (BusinessException)e;
  11. return ResultUtil.error(businessException.getCode(), businessException.getMessage());
  12. }
  13. //未知错误
  14. return ResultUtil.error(- 1, "系统异常:\\n"+e);
  15. }
  16. }
判断这个是否是业务异常。和系统异常就可以分开处理了。


猜你喜欢

转载自blog.csdn.net/white_ice/article/details/80980814