簡體   English   中英

Spring Boot - 處理 NoHandlerFoundException

[英]Spring Boot - Handling NoHandlerFoundException

閱讀關於如何處理NoHandlerFoundException春參考指南,發現彈簧套,默認情況下, throwExceptionIfNoHandlerFoundfalse

知道這一點后,我認為將此參數設置為true是個好主意。

我正在使用 Spring Boot。

這樣做了:

配置文件

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@SpringBootApplication
public class MyConfig {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MyConfig.class, args);
        context.getBean(DispatcherServlet.class).setThrowExceptionIfNoHandlerFound(true);

        // ...
    }
}

好的,現在throwExceptionIfNoHandlerFound等於true 然而,這並沒有像預期的那樣奏效。 DispatcherServlet繼續不拋出NoHandlerFoundException 這樣一來,我就無法處理了。

CustomExceptionHandler.java (這不起作用)

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity <Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // do my own handle ...

        // then, return ...
    }

}

經過一番搜索,發現添加@EnableWebMvc應該可以。 然后,我確實將此注釋添加到我的CustomExceptionHandler

CustomExceptionHandler.java (這確實有效)

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@EnableWebMvc
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity <Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // do my own handle ...

        // then, return ...
    }

}

這樣,手柄就起作用了。 但是,我正在使用 Spring Boot。 Spring Boot 文檔表明,如果我插入@EnableWebMvc ,我將失去一些 Spring Boot MVC 自動配置功能,因為我將完全控制 Spring MVC。 見這里)。

“如果你想完全控制 Spring MVC,你可以添加你自己的 @Configuration 用 @EnableWebMvc 注釋。”

我會丟失 Spring MVC 自動配置嗎? 我的意思是, @EnableWebMvc ,就我而言,它不在@Configuration類中。

我的問題是基於這樣一個事實,即我不確定上面的代碼是如何工作的,我想知道是否有另一種方法可以在不丟失 Spring MVC 自動配置的情況下執行此操作。 有人能解釋一下嗎?

Spring Boot 自動配置會自動添加一個ResourceHttpRequestHandler來處理服務靜態資源。 默認情況下,此處理程序映射到/**並且是處理程序鏈中的最后一項。

這意味着DispatcherServlet不會拋出NoHandlerFoundException因為它找到了資源處理程序。 資源處理程序處理請求並調用response.sendError(HttpServletResponse.SC_NOT_FOUND)以返回 404。

如果您不想要這種行為,您可以將以下內容添加到您的application.properties

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

將配置調度程序 servlet 以拋出異常告訴 Spring Boot 不要注冊資源處理程序。

在沿着這條路線走得太遠之前,您可能需要查看參考文檔的這一部分,看看以不同的方式處理這些錯誤是否更好。 從您的問題中並不完全清楚您在錯誤處理程序中實際嘗試做什么,但如果它只是處理 404,那么可能有更好的方法。

import java.util.Date;


import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


@ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {
    static Logger logger = Logger.getLogger(ExceptionController.class.getName());

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    @Override
    protected ResponseEntity <Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
                request.getDescription(false));
        
            logger.error(request);
        return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM