构建SpringBoot实战项目 系列文章之自定义返回状态码和异常信息。

第一次写博客,暂时在构建一个SpringBoot后台项目 前端准备采取Vue,后台采取java 准备集成SpringBoot+shiro+mybaits基础上开展的用户的权限管理,定时任务,微信公众号等。

第一篇 关于SpringBoot自定义异常:

   第一步,创建自定义异常,源码如下:

BizException:
public class BizException extends RuntimeException {
    private String code;  //错误码

    public BizException() {
    }

    public BizException(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.code = errorCode.getCode();
    }


    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
 
 
自定义异常编码:
public interface ErrorCode {
    String getMessage(Object... var1);

    String getCode();
}
public enum CMMErrorCode implements ErrorCode {
    
    //用户
    USER_TITLE_IS_EXISTS("1000"),
    //错误
     EROR("9999");

    private static HashMap<ErrorCode, String> map = new HashMap<>();

    static {

        map.put(CMMErrorCode.USER_TITLE_IS_EXISTS, "用户标题已经存在");

    }

    private static ErrorMessage errorMessage = new ErrorMessage(map);

    private String code;

    CMMErrorCode(String code) {
        this.code = code;
    }

    public String getMessage(Object... args) {
        return errorMessage.getErrorMessage(this, args);
    }

    public String getCode() {
        return code;
    }
}
第二步,创建配置handler:
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Map defultExcepitonHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        Map map = new HashMap();
        if(e instanceof BizException) {
            BizException businessException = (BizException)e;
            map.put("code", businessException.getCode());
            map.put("msg", businessException.getMessage());
        }else{
            map.put("code", -1);
            map.put("msg", "系统异常");
        }
        //未知错误
        return map;
    }
}

有关注解的讲解,

@ControllerAdvice是组件注解,他使得其实现类能够被classpath扫描自动发现,如果应用是通过MVC命令空间或MVC Java编程方式配置,那么该特性默认是自动开启的。

注解@ControllerAdvice的类可以拥有@ExceptionHandler, @InitBinder或 @ModelAttribute注解的方法,并且这些方法会被应用到控制器类层次的所有@RequestMapping方法上。

而 @RestControllerAdvice 是@ControllerAdvice+@ResponseBody.

第三步:运用:

建立BizException的子类

public class ResponseException extends BizException{

    public ResponseException(CMMErrorCode errorCode) {
        super(errorCode);
    }

}
在业务的实际运用:
//验证用户登录名是否重复
protected void throwIfExistAccount(String title) {
    if (existTitle(title)!=null) {
        throw new ResponseException(CMMErrorCode.USER_TITLE_IS_EXISTS);
    }
}

代码产生效果:



猜你喜欢

转载自blog.csdn.net/weixin_35282902/article/details/80794717