自定义响应体拦截器

1.自定义异常抛出格式

继承自ResponseBodyAdvice

@Slf4j
@Order(1)
执行顺序优先级  
                        
@RestControllerAdvice(value = "com.fitmgr.ces")
指定包响应体都会受到拦截     

public class ResponseBodyWrapper implements ResponseBodyAdvice {
    @ExceptionHandler(Exception.class)   
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    处理响应状态码为500 的异常

    public RB handleGlobalException(Exception e) {
        log.error("GOT SYS EXCEPTION: ", e);
        return new RB<>(ReturnCodes.EXECUTE, ReturnCodes.EXECUTE.getMsg());
    }

    @ExceptionHandler(BaseException.class)
    public RB handleGlobalException(BaseException exception, HttpServletResponse response) {
        log.error("GOT INTERNAL EXCEPTION: ", exception);
        response.setStatus(exception.getHttpStatus().value());
        return new RB<>(exception.getCode(), exception.getMessage());
    }

    @ExceptionHandler(RestClientException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RB handleGlobalException(RestClientException exception) {
        log.error("GOT EXCEPTION: ", exception);
        return new RB<>(ReturnCodes.EXECUTE, exception.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public RB handleGlobalException(DuplicateKeyException exception) {
        log.error("GOT DuplicateKeyException: ", exception);
        return new RB<>(ReturnCodes.DUPLICATE_RESOURCE_EXCE, exception.getCause().getMessage());
    }
    
    
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }
    
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return new RB<>();
        } else if (body instanceof RB) {
            return body;
        }
        return new RB<>(body);
    }
    
    如果没有响应体则返回空的RB对象
    如果响应体不是 RB对象则封装为RB对象
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值