springboot-异常处理

整体概览

先来看整体的结构图:(广东人:丢你老味)

具体操作

先在pojo层定义一个异常的实体类ErrorResponse,在这里我们可以自定义我们想要的对象,比如这里我想要返回状态码,错误码以及错误信息:

@Data
public class ErrorResponse {
    private int status;
    private String errorCode;
    private String message;

    public ErrorResponse(int status, String errorCode, String message) {
        this.status = status;
        this.errorCode = errorCode;
        this.message = message;
    }
    public ErrorResponse(String errorCode, String message) {
        this.errorCode = errorCode;
        this.message = message;
    }
}

在exception文件夹定义一个异常类ProductNotfoundException:

@EqualsAndHashCode(callSuper = true)
@Data
public class ProductNotfoundException extends RuntimeException {
    private String errorCode;

    public ProductNotfoundException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
}

在controller层,定义ProductExceptionController类。在这里我们写入返回的状态码HttpStatus:

@ControllerAdvice
public class ProductExceptionController {
    @ExceptionHandler(value = ProductNotfoundException.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> exception(ProductNotfoundException exception) {
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), exception.getErrorCode(), exception.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.OK);
    }
}

 再定义一个应用异常的服务控制类ProductServiceController。在这里我们写入我们自定义的错误码--errorCode,错误信息--message:

@RestController
public class ProductServiceController {
    @PutMapping(value = "/products/{id}")
    public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
        if(!productRepo.containsKey(id)) throw new ProductNotfoundException("40004", "Not found qaq");
        productRepo.remove(id);
        product.setId(id);
        productRepo.put(id, product);
        return new ResponseEntity<>("product update success", HttpStatus.OK);
    }
}

结果展示

用postman调试接口,会得到一个异常信息对象。会了吗,番薯(在广东番薯是大帅哥的意思)

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值