最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot的統(tǒng)一異常處理,使用@RestControllerAdvice詳解

 更新時(shí)間:2024年12月14日 14:53:49   作者:無足鳥丶  
@RestControllerAdvice是Spring Boot中的全局異常處理注解,結(jié)合了@ControllerAdvice和@ResponseBody的功能,通過創(chuàng)建自定義異常類和全局異常處理器,可以實(shí)現(xiàn)統(tǒng)一異常處理,確保API的一致性和響應(yīng)的標(biāo)準(zhǔn)化

springboot統(tǒng)一異常處理,使用@RestControllerAdvice

@RestControllerAdviceSpring Boot 中用于全局異常處理的注解,它結(jié)合了 @ControllerAdvice@ResponseBody 的功能。

這意味著使用 @RestControllerAdvice 注解的類將應(yīng)用于所有 @RequestMapping 方法,并且任何從這些方法返回的對(duì)象都會(huì)被轉(zhuǎn)換為 HTTP 響應(yīng)體。

下面是如何使用 @RestControllerAdvice 實(shí)現(xiàn)統(tǒng)一異常處理的一個(gè)示例:

創(chuàng)建自定義異常類

首先,創(chuàng)建一些自定義異常類來表示不同的錯(cuò)誤情況。

例如:

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

定義API錯(cuò)誤響應(yīng)格式

為了確保API返回的一致性,可以創(chuàng)建一個(gè)標(biāo)準(zhǔn)的錯(cuò)誤響應(yīng)結(jié)構(gòu),如 ApiError 類:

public class ApiError {
    private HttpStatus status;
    private String message;
    private LocalDateTime timestamp;

    public ApiError(HttpStatus status, String message, Throwable throwable) {
        this.status = status;
        this.message = message;
        this.timestamp = LocalDateTime.now();
    }

    // Getters and Setters...
}

使用@RestControllerAdvice創(chuàng)建全局異常處理器

然后,你可以創(chuàng)建一個(gè)帶有 @RestControllerAdvice 注解的類,用來處理不同類型的異常:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiError> handleResourceNotFoundException(ResourceNotFoundException ex) {
        ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getMessage(), ex);
        return new ResponseEntity<>(apiError, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiError> handleAllExceptions(Exception ex) {
        ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, "An error occurred", ex);
        return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 你可以添加更多特定的 @ExceptionHandler 方法來處理其他類型的異常
}

配置全局異常屬性(可選)

你還可以在 application.propertiesapplication.yml 文件中配置一些全局的行為,

例如是否顯示堆棧跟蹤信息:

# application.properties
server.error.include-stacktrace=never

或者在 YAML 文件中:

# application.yml
server:
  error:
    include-stacktrace: never

通過這種方式,@RestControllerAdvice 提供了一種簡(jiǎn)潔的方法來集中處理整個(gè)應(yīng)用程序中的異常,確保所有異常都能以一致的方式響應(yīng)客戶端請(qǐng)求。

此外,由于它自帶了 @ResponseBody 功能,所以特別適合 RESTful Web 服務(wù)。

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

丰城市| 宜良县| 昌都县| 贺州市| 普陀区| 临沧市| 庆阳市| 吴忠市| 芦山县| 疏附县| 泸西县| 泰州市| 黄大仙区| 肥城市| 渝中区| 武清区| 古交市| 昭觉县| 礼泉县| 盐津县| 中西区| 苗栗县| 安义县| 普陀区| 辛集市| 改则县| 盘锦市| 新宾| 祁连县| 巴青县| 丽江市| 衡山县| 汪清县| 和静县| 子长县| 辰溪县| 蛟河市| 永胜县| 温州市| 和林格尔县| 乌拉特中旗|