自定义返回异常
发布日期:2021-05-08 14:12:39 浏览次数:20 分类:精选文章

本文共 2944 字,大约阅读时间需要 9 分钟。

Spring 异常处理与友好提示优化方案

项目背景与技术选型

本项目旨在实现一个友好提示的异常处理机制,确保在价格字段未输入时返回特定的HTTP状态码和用户友好的提示信息。为此,我们选择了以下技术方案:

1. Restful API 设计

  • 使用 @RestController 定义RESTful API接口。
  • 返回类型为 ResponseEntity,以支持HTTP状态码和自定义响应内容。

2. 异常处理机制

采用Spring的异常处理机制,通过自定义异常和@ControllerAdvice实现全局异常处理。


自定义异常实现

1. 定义自定义异常类

@Getterpublic class LyException extends RuntimeException {    private int status;    private String message;        public LyException(ExceptionEnum em) {        super(em.getMessage());        this.status = em.getStatus();    }        public LyException(ExceptionEnum em, Throwable cause) {        super(em.getMessage(), cause);        this.status = em.getStatus();    }}

2. 定义异常状态码枚举

@Getterpublic enum ExceptionEnum {    PRICE_CANNOT_BE_NULL(400, "价格不能为空");        private int status;    private String message;        ExceptionEnum(int status, String message) {        this.status = status;        this.message = message;    }}

异常处理逻辑

1. 全局异常处理类

import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import tech.ligang.example.ItemController;import tech.ligang.example.ExceptionResult;import java.time.LocalDateTime;@RestControllerAdvicepublic class BasicExceptionAdvice {        private final Logger log = LoggerFactory.getLogger(BasicExceptionAdvice.class);        @ExceptionHandler(LyException.class)    public ResponseEntity
handleLyException(LyException le) { log.error("发生异常:{}", le.getMessage(), le); return ResponseEntity.status(le.getStatus()) .body(new ExceptionResult(le)); }}

2. 异常处理结果

@Getterpublic class ExceptionResult {    private int status;    private String message;    private String timestamp;        public ExceptionResult(LyException e) {        this.status = e.getStatus();        this.message = e.getMessage();        this.timestamp = LocalDateTime.now().toString("yyyy-MM-dd HH:mm:ss");    }}

实现步骤说明

1. 定义 RESTful 接口

@RestControllerpublic class ItemController {    @PostMapping("/item")    public ResponseEntity
save(@RequestBody Item item) { item.setId(1L); if (item.getPrice() == null) { throw new LyException(ExceptionEnum.PRICE_CANNOT_BE_NULL); } return ResponseEntity.status(HttpStatus.CREATED) .body(item); }}

2. 异常处理逻辑

@ExceptionHandler(LyException.class)public ResponseEntity
handleLyException(LyException le) { return ResponseEntity.status(le.getStatus()) .body(new ExceptionResult(le));}

3. 测试验证

当价格字段未输入时,系统会抛出 LyException 异常,并通过 BasicExceptionAdvice 进行处理,返回如下友好提示:

{    "status": 400,    "message": "价格不能为空",    "timestamp": "2023-10-01 10:00:00"}

总结

通过以上方案,我们实现了在价格字段未输入时,返回友好提示和特定HTTP状态码的功能。该方案不仅满足了业务需求,还确保了系统的健壮性和可维护性。

上一篇:IDEA快捷键
下一篇:技术美术面试问题整理

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年03月21日 06时48分54秒