Skip to main content

Custom error handling in Spring Boot 404 not found and 5xx internal server error

We are familiar with the well known whitelabel error in Spring Boot. It appears when the application will not find the resource the user is looking for or any internal application error. This application will demonstrate on how to handle these errors. Spring Boot 1.5.3 has made it easy to handle such error by providing the easy implementation on the user side.
First, let us create a simple Spring Boot application. You can use any IDE or go to start.spring.io and create your project. After creating your project, run it as Java application (In eclipse, right click the project -> Run as -> Java Application) or Spring Boot application if you have STS installed. You can download the source code from here. Now, try to access localhost:8080 and you'll see the first whitelabel error because spring boot application is looking for index.html but we haven't defined anything in our application. So, you'll see the error like this.
White label error

Now, let us create index.html inside src/main/resources/templates folder like in the below picture
index page
and write something like this.
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8"/>
 <title>Spring Boot Custom error handling</title>
</head>
<body>
 <p>Demo application for custom error handling in Spring Boot</p>
</body>
</html>

Let's create a PageController and define the route to index.html, this way we'll not see the whitelabel error when we try to access localhost:8080

package pro.budthapa.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class PageController {
    private static final String INDEX= "index";
    
    @GetMapping("/")
    public String index(){
 return INDEX;
    }
}
Now, try to access localhost:8080, you'll be greeted with your index.html page
Demo application for handling custom error in spring boot

Handle 404 error in Spring Boot

But if you want to access other resources like localhost:8080/something then you'll get the whitelabel error with status code 404. To handle this, let us create a error folder inside src/main/resources/templates/. Inside this folder create a file named 404.html
Error folder
Write some messages inside 404.html page that is easy for the user to understand or your own messages
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>404 Not found</title>
</head>
<body>
    <p>404 Error. Oops! The resource you are looking is not found.</p>
</body>
</html>
Try to access localhost:8080/asfd or any non existent url and you'll be greeted with the custom 404 not found message
spring boot 404 not found

Let us handle the 500 Internal server error in Spring Boot

First, let us create method named about inside the PageController and point it to about.html page.
package pro.budthapa.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class PageController {
 private final String INDEX= "index";
 private final String ABOUT= "about";
 
 @GetMapping("/")
 public String index(){
  return INDEX;
 }
 
 @GetMapping("/about")
 public String about(){
  return ABOUT;
 }
 
}
Now, run localhost:8080/about in your browser, but wait! there is not any about.html page defined in our project. You'll now get error with status code 500
500 internal server error spring boot
To handle this error, create 5xx.html file inside the previous /error folder. Here, 5xx means 500, 501, 503, etc.
Write meaningful message inside this 5xx.html page
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>5xx error handling</title>
</head>
<body>
    <p>Handling error with status code 5xx. eg: 500, 503 etc. </p>
</body>
</html>
Now, try to run localhost:8090/about in your browser and you'll get the above message you've defined.
handling 500 internal server error in spring boot
We've created our own custom error handling in Spring Boot. You can download the source code from here.

Comments

  1. Is there a way to do this while also including logging on a controller as well as a common error page for all errors not caught?

    ReplyDelete
  2. Yes you can do it. Use @ControllerAdvice annotation. Check here

    ReplyDelete

Post a Comment

Popular posts from this blog

Live video streaming with ffmpeg and ffserver

Live video and audio streaming with ffmpeg and ffserver This is a guide on how to stream video using ffserver and ffmpeg in ubnutu. The ffmpeg ffserver version used is 3.3-1~16.04.york1. You can download ffserver from ffmpeg.org . I'm using linux mint 18. So, I've downloaded ffmpeg from the repository. You can follow the link below to install the latest version of ffmpeg. Install ffmpeg in linux mint 18 using command line . First, we need to setup our ffserver.conf to stream the audio and video properly. ffserver.conf file is usually located in /etc/ffserver.conf. You can either edit the ffserver.conf or create your own .conf file. I'll be creating my own .conf file named livestream.conf In console, type sudo nano /etc/livestream.conf Blank .ffm file will be created. Now, enter the required properties for streaming live video using ffserver #Default port HTTPPort 8090 HTTPBindAddress 0.0.0.0 MaxHTTPConnections 2000 MaxClients 1000 MaxBandwidth 100000 Custo...

Handling unexpected runtime exception inside Thread. thread.setUncaughtExceptionHandler

Create and set UncaughtExceptionHandler before starting new thread to catch unexpected runtime exception in Multithreading application. package demo; public class ExceptionHandler {     public static void main(String[] args) {         Thread thread = new Thread(new Runnable() {             @Override             public void run() {                 throw new RuntimeException("Critical Error");             }         });         System.out.println("Starting new thread " + Thread.currentThread().getName());         //Throw this exception if any exception has occurred inside running thread but was not cau...

Spring Security with Spring Boot and MySQL

Spring Security with Spring Boot and MySQL In this tutorial I'll show how to use Spring Security with Spring Boot and MySQL. We'll implement a UserDetailsService provided by Spring Security. It is easy to configure Spring Security with Spring Boot and MySQL. You can also check how to run Spring Boot application inside docker container Steps: 1. Create a Spring Boot project from start.spring.io with following dependencies in your pom.xml file. You can choose gradle also for project dependencies. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- dev tools for hot reloading --> <dependency> <groupId>org.springframework.b...