统一处理异常思路

统一处理异常思路

1、自定义异常 BusinessException

public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public BusinessException(String message) {
        super(message);
    }
}

2、统一响应

public class CommonResponse implements Serializable {

    private static final long serialVersionUID = 1L;

    private String message = "";

    public CommonResponse(final String message) {
        this.message = message;
    }

    public CommonResponse() {

    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

3、异常统一处理 @ControllerAdvice

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<CommonResponse> handleExcepting(BusinessException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .contentType(MediaType.APPLICATION_JSON)
                .body(new CommonResponse(e.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<CommonResponse> handleExcepting(Exception e) {
        log.error("error", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(new CommonResponse("服务器内部错误"));
    }

}

4、应用Demo

 	@Authorization
    @PostMapping("profile")
    public AdminVo getAdminInfo() {
        AdminVo adminVo = adminService.getAdminInfo();
        if (adminVo == null) {
            throw new BusinessException("自定义异常");
        }
        return adminVo;
    }

好处:给前端统一的响应,便于处理

@ControllerAdvice ???

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值