spring-boot

时间:2017-03-16 13:29:16

标签: spring-mvc model-view-controller spring-boot exception-handling

我正在尝试在SpringMvc(Spring-boot 1.5.1版)中为无效URL创建自定义错误页面。

为了禁用默认的whitelabel错误页面,我有:

application.properties

spring.thymeleaf.cache=false
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

我的异常处理程序是:

RestResponseEntityExceptionHandler.java

@ControllerAdvice 
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    public RestResponseEntityExceptionHandler() {
        super();
    }

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.error("404 Status Code", ex);
        final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("No such page", null, request.getLocale()), "NoHandlerFound");
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }
}

原则上这是有效的。如果我在浏览器中找到无效的URL,我会得到一个类似的JSON:

  

{&#34; message&#34;:&#34;没有这样的页面&#34;,&#34;错误&#34;:&#34; NoHandlerFound&#34;}

我希望显示正确的HTML视图(类似于whitelabel页面),而不是JSON响应。这应该是一个模板,我可以替换&#34;消息&#34;串。我该如何渲染这个视图?

1 个答案:

答案 0 :(得分:7)

使用Spring Boot&amp; Spring MVC你可以在resources / public下创建一个错误文件夹并放置你的客户错误页面。春天会接他们。

src/
+- main/
   +- java/
   |   + <source code>
   +- resources/
       +- public/
           +- error/
           |   +- 404.html
           +- <other public assets>

如果您不使用Spring MVC,则必须通过实施自己的错误页面注册商来注册错误页面。

@Bean
public ErrorPageRegistrar errorPageRegistrar(){
    return new MyErrorPageRegistrar();
}

private static class MyErrorPageRegistrar implements ErrorPageRegistrar {

    // Register your error pages and url paths.
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
    }

}

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling-custom-error-pages