Whitelabel error page что это
Перейти к содержимому

Whitelabel error page что это

  • автор:

Отключить страницу ошибки Whitelabel в Spring Boot

В этом посте мы обсудим, как отключить страницу ошибок Whitelabel в Spring Boot.

Мы знаем, что Spring Boot отображает страницу ошибки Whitelabel, если вы сталкиваетесь с ошибкой сервера. Типичная страница ошибки Whitelabel в клиентском браузере выглядит следующим образом:

Whitelabel Error Page
This application has no explicit mapping for /error, so you see this as a fallback.

Tue Dec 25 14:23:07 IST 2018
There was an unexpected error (type=Not Found, status=404).
No message available

Существует несколько способов отключить страницу ошибок Whitelabel по умолчанию в Spring Boot и заменить ее страницей ошибок вашего контейнера сервлетов. Мы также можем добавить вашу собственную страницу ошибки, а не отключать ее полностью, и отправить клиенту разумный ответ с правильным кодом ошибки.

1. Файл свойств

Если мы установим server.error.whitelabel.enabled собственность на false в application.properties или же application.yml , он отключает страницу ошибки по умолчанию. Это приведет к тому, что вместо этого будут отображаться страницы ошибок контейнера сервлетов. Например, встроенный контейнер tomcat теперь отображает сообщение об ошибке ‘HTTP Status 404 — Not Found’.

2. Исключение bean-компонента ErrorMvcAutoConfiguration

Мы также можем отключить ErrorMvcAutoConfiguration bean внутри основного класса, чтобы удалить страницу ошибки Whitelabel. Это также восстановит страницу ошибок по умолчанию для контейнера сервлетов, который вы используете.

Introduction

Alexander Obregon

Spring Boot, a significant project in the Spring Framework universe, has been a boon for Java developers worldwide, simplifying the task of creating stand-alone, production-grade Spring applications. In a nutshell, it makes it easy to just “run”. Among its extensive feature set, Spring Boot’s default error handling, also known as “WhiteLabel Error Handling”, is a standout. This blog post will deep-dive into Spring Boot’s WhiteLabel Error handling, providing insights into its functionalities, how to customize it, and its overall significance in the development process.

What is WhiteLabel Error Handling?

In Spring Boot, the term “whitelabel” refers to the default behavior of a service. In the case of error handling, the “WhiteLabel Error Page” is the default page that is displayed when an exception occurs. For instance, when you encounter a “404 Not Found” error or a “500 Internal Server Error”, Spring Boot automatically displays a basic error page. This is all thanks to the WhiteLabel error handling mechanism that comes out of the box with Spring Boot.

The Underlying Mechanism

The WhiteLabel error handling mechanism is an implementation of the ErrorController, an interface in the Spring Boot framework. This interface, by default, is overridden by the BasicErrorController that provides the white-label error handling functionality.

Whitelabel Error Page in Spring Boot | Complete Guide

Let’s learn about the Whitelabel error page in Spring Boot and how to customize or disable them. White label error pages are default behavior from Spring Boot. Like any other feature, We can customize this feature to great extent.

What are Whitelabel error pages in Spring Boot?

Depending on API client request or browser request, spring boot provides an error JSON response or a full HTML error page. For example, let’s create a simple /hello endpoint that throws an exception always.

Whitelabel error page showing a generic information about an error

Even though this page looks simple, you can add details to it using the following configuration.

whitelabel error page with details

Even though the messages are helpful, this page may not fit well with your other page designs. So if you want to override this page with your own design, you are in luck.

Overriding Whitelabel Error Pages

Spring boot provides a /error mapping at a global servlet container level. This mapping handles requests and sends back JSON or HTML view as a response with error codes/messages. But the view that we saw above looks default. If you notice the first line of the error page, it says “This application has no explicit mapping for /error, so you are seeing this as a fallback.”

Here, the spring boot is trying to hint to you that you need to provide your own template to handle these error requests. So let’s see how to do that.

As we know, The handler mapped for /error expects a view to show the HTML response. If it doesn’t find a view matching “error” it will use the placeholder we have seen above. So we first need to add a template called error.html. But the template alone will not work. You also need to add one of the spring boot supported template engines. In our case, we are adding thymeleaf.

Next, you need to add the error.html template into your src/main/resources/templates directory.

With the above in place, the following MVC attributes will be available for you to access in the templates.

  1. message – Return value of exception.getMessage()
  2. exception – A string that contains the canonical exception name.
  3. trace – The complete stacktrace of the exception that caused this error.
  4. errors – A list of validation failures that occured during the request.

Along with these, there is also a status attribute that gives the HTTP status code for the error response. With that in place, we can rewrite our template file to show all these attributes.

This simple template will yield the following error page when we access /hello.

whitelabel page showing error details

With a little bit of CSS, we can get this page to look better and more appealing.

Custom error page with details and CSS

Disabling Whitelabel error page altogether /Tomcat whitelabel

Spring boot also provides a way to disable the Whitelabel error page altogether using server.error.whitelabel.enabled setting. When set to false, the server will show an error page specific to the servlet container(tomcat). For example, the below error page from tomcat will be visible if the Whitelabel is disabled and no error template is available.

Tomcat error page when whitelabel is disabled

You can swap tomcat with jetty and you will still see an error page like this offered by the jetty runtime. And undertow currently doesn’t provide a view. But it does send response codes.

Important things to note

Always use a custom error.html page for the following reasons.

  1. Default whitelabel page lets hackers know you are using spring boot. This means they only need to try the exploits for spring boot.
  2. Never show exceptions in your production servers. Exceptions are great info for hackers.
  3. A custom error page with proper CSS will blend in to your other pages. You can even provide links and search boxes that can redirect users back to your site.

You can hide specific error attributes based on the configuration we saw earlier. Also, all these configurations are also applicable for the JSON response as well. If your request contains Accept: application/json header, then the response will be in the form of JSON. Even here, you can access all these attributes. For example, take a look at the below request.

Here you can see the trace, exception, and message attributes being available as JSON.

Почему возникла ошибка Whitelabel?

Ситуация следующая:
Спринг начал выдавать Whitelabel Error Page.
Пробовал пересоздать контроллер и проект целиком, проблема не ушла.
Гугл подсказал, что это может быть связано с пакетами, но у меня с пакетами вроде все правильно.
В чем может быть причина?

  • Вопрос задан более года назад
  • 5312 просмотров

Простой 3 комментария

  • Facebook
  • Вконтакте
  • Twitter

sergueik

во первых — вопрос какой порт и урл вы открываете что получаете 404 ?
во вторых что то у вас маловато аннотаций что слушает контроллер и это понятное дело надо поправить така как вы ответите нп первый вопрос

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *