放置常用的一些响应信息
javapublic enum ResultCodeEnum {
ERROR(100, "系统错误"),
SUCCESS(200, "操作成功"),
FAILED(500, "操作失败");
VALIDATE_FAILED(404, "参数检验失败"),
UNAUTHORIZED(401, "暂未登录或token已经过期"),
FORBIDDEN(403, "没有相关权限");
// 自定义状态码
private final int code;
// 自定义描述
private final String msg;
ReturnCode(int code, String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
设置一个响应的包装类 包含一些响应状态码、响应消息、响应数据、接口请求时间等
javapublic class CommonResult<T> {
private long code;
private String message;
private T data;
protected CommonResult() {
}
protected CommonResult(long code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <T> CommonResult<T> success(T data) {
return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), data);
}
/**
* 成功返回结果
*
* @param data 获取的数据
* @param message 提示信息
*/
public static <T> CommonResult<T> success(T data, String message) {
return new CommonResult<T>(ResultCodeEnum.SUCCESS.getCode(), message, data);
}
/**
* 失败返回结果
* @param errorCode 错误码
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode) {
return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
}
/**
* 失败返回结果
* @param message 提示信息
*/
public static <T> CommonResult<T> failed(String message) {
return new CommonResult<T>(ResultCodeEnum.FAILED.getCode(), message, null);
}
/**
* 失败返回结果
*/
public static <T> CommonResult<T> failed() {
return failed(ResultCodeEnum.FAILED);
}
/**
* 参数验证失败返回结果
*/
public static <T> CommonResult<T> validateFailed() {
return failed(ResultCodeEnum.VALIDATE_FAILED);
}
/**
* 参数验证失败返回结果
* @param message 提示信息
*/
public static <T> CommonResult<T> validateFailed(String message) {
return new CommonResult<T>(ResultCodeEnum.VALIDATE_FAILED.getCode(), message, null);
}
/**
* 未登录返回结果
*/
public static <T> CommonResult<T> unauthorized(T data) {
return new CommonResult<T>(ResultCodeEnum.UNAUTHORIZED.getCode(), ResultCodeEnum.UNAUTHORIZED.getMessage(), data);
}
/**
* 未授权返回结果
*/
public static <T> CommonResult<T> forbidden(T data) {
return new CommonResult<T>(ResultCodeEnum.FORBIDDEN.getCode(), ResultCodeEnum.FORBIDDEN.getMessage(), data);
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
java
/**
* 描述:通用业务异常
* @author lhw
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class BusinessException extends RuntimeException{
/**
* 异常编码
*/
private String code;
/**
* 通过枚举类创建异常对象
* @param resultCodeEnum 枚举类
*/
public BusinessException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
}
/**
* 通过状态码和错误消息创建异常对象
* @param code 状态码
* @param message 错误消息
*/
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
}
java@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理请求参数校验错误:针对@RequestBody使用@Valid注解校验
* @param e 校验失败异常
* @param request request请求类
* @return 全局统一返回结果类
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<String> handler(HttpServletRequest request, MethodArgumentNotValidException e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
String message = e.getBindingResult().getAllErrors().stream().map(
DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
return Result.fail(ResultCodeEnum.ERR_0x1001.getCode(), message);
}
/**
* 处理请求参数校验错误:单个参数校验异常抛出,针对@RequestParam上增加校验注解,并在类上标注@Validated
* @param request request请求类
* @param e 校验失败异常
* @return 全局统一返回结果类
*/
@ExceptionHandler(ConstraintViolationException.class)
public Result<String> handler(HttpServletRequest request, ConstraintViolationException e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
String message = e.getConstraintViolations().stream().map(
ConstraintViolation::getMessage).collect(Collectors.joining(","));
return Result.fail(ResultCodeEnum.ERR_0x1001.getCode(), message);
}
/**
* 处理请求参数校验错误:针对表单类型的提交,即使用form data方式调用接口,进行参数校验错误时会抛出BindException异常
* @param request request请求类
* @param e 校验失败异常
* @return 全局统一返回结果类
*/
@ExceptionHandler(BindException.class)
public Result<String> handler(HttpServletRequest request, BindException e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
return Result.fail(ResultCodeEnum.ERR_0x1001.getCode(), Objects
.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
}
/**
* 绑定参数异常:如必须参数没传递
* @param request request请求类
* @param e 校验失败异常
* @return 全局统一返回结果类
*/
@ExceptionHandler(ServletRequestBindingException.class)
public Result<String> handler(HttpServletRequest request, ServletRequestBindingException e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
return Result.fail(ResultCodeEnum.ERR_0x1002);
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<String> handler(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
return Result.fail(ResultCodeEnum.ERR_0x1003);
}
@ExceptionHandler(BusinessException.class)
public Result<String> handler(HttpServletRequest request, BusinessException e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
return Result.fail(e.getCode(), e.getMessage());
}
/**
* 其他异常处理
* @param request request请求类
* @param e 异常
* @return 全局统一返回结果类
*/
@ExceptionHandler(Exception.class)
public Result<String> handler(HttpServletRequest request, Exception e) {
log.error("[全局统一异常处理]:异常URL:{},Message:{}", request.getRequestURL().toString(), e.getMessage(), e);
return Result.fail(ResultCodeEnum.ERR_0x1000.getCode(),e.getMessage());
}
}
java/**
* 描述:拦截Controller方法的返回值,统一处理返回值/响应体
*/
@RestControllerAdvice(basePackages = {"com.lhw.controller"})
public class ResultAdvice implements ResponseBodyAdvice<Object> {
@Autowired
private ObjectMapper objectMapper;
@Override
public boolean supports(MethodParameter methodParameter,
Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
if(o instanceof String){
return objectMapper.writeValueAsString(Result.success(o));
}
if(o instanceof Result){
return o;
}
return Result.success(o);
}
}
java
@GetMapping
public Result<IPage<User>> selectAll(Page<User> page, User user) {
return Result.success(this.userService.page(page, new QueryWrapper<>(user)));
}
错误的话就抛出 Result.fail();
或者填入一些自定义的状态码和响应消息
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!