优雅处理封装返回

前言

大家写代码可能会使用try…catch处理异常,当然spring mvc 架构中各层会出现大量的try {…} catch {…} finally {…}代码块,不仅有大量的冗余代码,而且还影响代码的可读性。下面推荐大家这样处理,既方便代码也显得更加规范优雅,真的香的不行。

推荐理由:

  • 代码复制到项目中通过简单的配置即可实现
  • 可以灵活的根据自己的业务异常进行更细粒度的扩展以及异常的处理返回

处理步骤大致如下:

  • 封装统一返回结果类
  • 自定义异常封装类
  • 错误枚举类
  • 全局异常处理类
  • 测试

1:封装实体返回结果类

public class AjaxResult {
    //是否成功
    private Boolean success;
    //状态码
    private Integer code;
    //提示信息
    private String msg;
    //数据
    private Object data;
    //无参构造
    public AjaxResult() {

    }
    //自定义返回结果的构造方法
    public AjaxResult(Boolean success,Integer code, String msg,Object data) {
        this.success = success;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    //自定义异常返回的结果
    public static AjaxResult defineError(BusinessException de){
     AjaxResult result = new AjaxResult();
        result.setSuccess(false);
        result.setCode(de.getErrorCode());
        result.setMsg(de.getErrorMsg());
        result.setData(null);
        return result;
    }
    //其他异常处理方法返回的结果
    public static AjaxResult otherError(ErrorEnum errorEnum){
     AjaxResult result = new AjaxResult();
        result.setMsg(errorEnum.getErrorMsg());
        result.setCode(errorEnum.getErrorCode());
        result.setSuccess(false);
        result.setData(null);
        return result;
    }
 public Boolean getSuccess() {
  return success;
 }
 public void setSuccess(Boolean success) {
  this.success = success;
 }
 public Integer getCode() {
  return code;
 }
 public void setCode(Integer code) {
  this.code = code;
 }
 public String getMsg() {
  return msg;
 }
 public void setMsg(String msg) {
  this.msg = msg;
 }
 public Object getData() {
  return data;
 }
 public void setData(Object data) {
  this.data = data;
 }   
}

2:自定义异常封装类

public class BusinessException extends RuntimeException {

 private static final long serialVersionUID = 1L;
 /**
  * 错误状态码
  */
 protected Integer errorCode;
 /**
  * 错误提示
  */
 protected String errorMsg;

 public BusinessException(){
     }

 public BusinessException(Integer errorCode, String errorMsg) {
         this.errorCode = errorCode;
         this.errorMsg = errorMsg;
     }

 public Integer getErrorCode() {
  return errorCode;
 }

 public void setErrorCode(Integer errorCode) {
  this.errorCode = errorCode;
 }

 public String getErrorMsg() {
  return errorMsg;
 }

 public void setErrorMsg(String errorMsg) {
  this.errorMsg = errorMsg;
 }
}

3:错误枚举类


public enum ErrorEnum {
    /**
     * 参数错误 1000-1999
     */
    MISSING_REQUIRED_PARAMETER(1000, "缺少必填参数"), PARAM_INVALID(1001, "参数非法"),


    /**
     * 数据错误 2000-2999
     */
    DATA_NONE(2000, "数据未找到"), DATA_WRONG(2001, "数据错误"), DATA_EXISTED(2002, "数据已存在"),
    INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员"),
 ;

 /** 错误码 */
 private Integer errorCode;

 /** 错误信息 */
 private String errorMsg;

 ErrorEnum(Integer errorCode, String errorMsg) {
  this.errorCode = errorCode;
  this.errorMsg = errorMsg;
 }

    public Integer getErrorCode() {
        return errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }
}

4:全局异常处理类


/**
 * 全局异常处理器
 * 
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 处理自定义异常
     *
     */
    @ExceptionHandler(value = BusinessException.class)
    public AjaxResult bizExceptionHandler(BusinessException e) {
     log.error(e.getMessage(), e);
        return AjaxResult.defineError(e);
    }
    /**
     *处理其他异常
     *
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler( Exception e) {
      log.error(e.getMessage(), e);
        return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
      
    }
}

5:测试

@Api(tags = "查询管理")
@RestController
@RequestMapping("/machinery/experience")
public class ExperienceMachineryController extends BaseController {

    @ApiOperation(value = "查询管理")
    @PostMapping(value = "/query")
    public AjaxResult query() {
        throw new BusinessException(MISSING_REQUIRED_PARAMETER.getErrorCode(),MISSING_REQUIRED_PARAMETER.getErrorMsg());
    }

你可能感兴趣的:(异常处理,spring)