亲宝软件园·资讯

展开

Spring注解@RestControllerAdvice原理解析

人气:3

这篇文章主要介绍了Spring注解@RestControllerAdvice原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

前言

前段时间部门搭建新系统,需要出异常后统一接口的返回格式,于是用到了Spring的注解@RestControllerAdvice。现在把此注解的用法总结一下。

用法

首先定义返回对象ResponseDto

package com.staff.points.common;

import lombok.Data;

import java.io.Serializable;

@Data
public class ResponseDto<T> implements Serializable {
  private static final long serialVersionUID = -284719732991678911L;

  private String code;

  private String message;

  private T data;

  public static <T> ResponseDto<T> assemblingSuccessResponse(T data) {
    ResponseDto<T> responseDto = new ResponseDto<>();
    responseDto.setCode(ResponseCodeEnum.SUCCESS.getCode());
    responseDto.setMessage(ResponseCodeEnum.SUCCESS.getMessage());
    responseDto.setData(data);
    return responseDto;
  }

  public static <T> ResponseDto<T> assemblingSuccessResponse() {
    ResponseDto<T> responseDto = new ResponseDto<>();
    responseDto.setCode(ResponseCodeEnum.SUCCESS.getCode());
    responseDto.setMessage(ResponseCodeEnum.SUCCESS.getMessage());
    responseDto.setData(null);
    return responseDto;
  }

  public static <T> ResponseDto<T> assemblingFailureResponse(ResponseCodeEnum data) {
    ResponseDto<T> responseDto = new ResponseDto<>();
    responseDto.setCode(data.FAILURE.getCode());
    responseDto.setMessage(data.FAILURE.getMessage());
    return responseDto;
  }

  public static <T> ResponseDto<T> assemblingFailureResponse() {
    ResponseDto<T> responseDto = new ResponseDto<>();
    responseDto.setCode(ResponseCodeEnum.FAILURE.getCode());
    responseDto.setMessage(ResponseCodeEnum.FAILURE.getMessage());
    return responseDto;
  }
}

然后定义返回码的枚举类,此处只定义了两种,有需要可以往下添加很多。

package com.staff.points.common;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public enum ResponseCodeEnum {
  SUCCESS("00", "成功"),
  FAILURE("01", "系统异常");


  private String code;
  private String message;
}

下面是自定义的异常类

package com.staff.points.common;

import lombok.Data;

@Data
public class StaffPointsException extends RuntimeException{
  private String code;
  private String message;
  public StaffPointsException () {}

  public StaffPointsException (Exception e) {
    super(e);
  }

  public StaffPointsException (String code, String message) {
    super(message);
    this.code = code;
    this.message = message;
  }

  public StaffPointsException (ResponseCodeEnum codeEnum) {
    super(codeEnum.getMessage());
    this.code = codeEnum.getCode();
    this.message = codeEnum.getMessage();
  }
}

然后是关键的@RestControllerAdvice修饰的类

package com.staff.points.exception;

import com.staff.points.common.ResponseCodeEnum;
import com.staff.points.common.ResponseDto;
import com.staff.points.common.StaffPointsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Component
public class UnifyExceptionHandler {
  private Logger logger = LoggerFactory.getLogger(UnifyExceptionHandler.class);

  @ExceptionHandler(Exception.class)
  public ResponseDto handlerCommonException (Exception e) {
    ResponseDto responseDto = new ResponseDto<>();
    responseDto.setCode(ResponseCodeEnum.FAILURE.getCode());
    responseDto.setMessage(ResponseCodeEnum.FAILURE.getMessage());
    logger.info("UnifyExceptionHandler.handlerCommonException exception:" + e);
    return responseDto;
  }
  // 报StaffPointException时,对其进行拦截并处理的方法
  @ExceptionHandler(StaffPointsException.class)
  public ResponseDto handlerCustomizeException (StaffPointsException e) {
    ResponseDto responseDto = new ResponseDto<>();
    responseDto.setCode(e.getCode());
    responseDto.setMessage(e.getMessage());
    logger.info("UnifyExceptionHandler.handlerCustomizeException StaffPointsException:" + e);
    return responseDto;
  }
}

运行代码时,如果出现了StaffPointException,那么就会被拦截进入第27行的方法(就是说可以自由的在业务代码里往外throw自定义异常了);如果出现了其他的异常,则进入18行的方法,统一返回。

验证一下,在代码里造一个NPE异常时,返回结果:

 {
  "code": "01",
  "message": "系统异常",
  "data": null
 }

造一个StaffPointsException异常时,返回结果:

 {
  "code": "99",
  "message": "自定义业务异常",
  "data": null
 }

它的作用原理,大体是先在spring初始化时将类扫描进容器,出异常后,在DispatcherServlet类的doDispatch方法中调用了对异常的拦截处理。

小结

看@RestControllerAdvice源码可以知道,它就是@ControllerAdvice和@ResponseBody的合并。此注解通过对异常的拦截实现的统一异常返回处理,如果大家在项目中有类似的需求,不妨试一下,好用又方便。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论