第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用全局異常處理程序在 SpringBoot 應用程序中處理 BindException

使用全局異常處理程序在 SpringBoot 應用程序中處理 BindException

白衣非少年 2022-07-20 10:28:03
我有一個帶有發(fā)布請求的控制器。我正在嘗試使用簡單的 NotNull 注釋來驗證 POJO。我正在使用 ControllerAdvice 來處理異常。@PostMapping("/something")public MyResponse post(@Valid MyRequest request) {   // nevermind...}public class MyRequest {  @NotNull  private Integer something;  // Getters setters nevermind...}@ControllerAdvicepublic class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {    @ExceptionHandler(value = BindException.class)    protected ResponseEntity<Object> handleBindException(RuntimeException ex, WebRequest request) {        return handleExceptionInternal(...);    }}所以我正在嘗試使用它,但是當我啟動應用程序時,我得到了以下信息:org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.validation.BindException]: {protected org.springframework.http.ResponseEntity com.liligo.sponsoredads.controller.RestResponseEntityExceptionHandler.handleBindException(java.lang.Exception,org.springframework.web.context.request.WebRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest) throws java.lang.Exception}所以我想為 BindExceptions 創(chuàng)建自己的處理程序,但是當我為 BindException 類創(chuàng)建 ExceptionHandler 時,spring 應用程序沒有啟動。如果我注釋掉handleBindException 方法,應用程序將啟動,如果發(fā)生BindException,它只會返回400 并注銷錯誤,但沒有任何內容作為響應正文發(fā)回。為 BindExceptions 創(chuàng)建自定義處理程序的解決方案是什么?
查看完整描述

1 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

我發(fā)現(xiàn)問題是因為 ResponseEntityExceptionHandler 已經有一個方法來處理 BindExceptions。這意味著您不能為此“覆蓋”異常處理。許多異常也是如此(參見類 ResponseEntityExceptionHandler:106)。因此,如果您想創(chuàng)建自己的綁定異常處理程序,則需要覆蓋超類中處理它的方法。它看起來像這樣:


@Override

    protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers,

                                                         HttpStatus status, WebRequest request) {

    return handleExceptionInternal(...);

}

有了它,您可以退回任何您需要的東西。所以我只找到了這個解決方案,如果有人知道其他解決方案,請不要猶豫在這里寫:)


查看完整回答
反對 回復 2022-07-20
  • 1 回答
  • 0 關注
  • 302 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號