error error handling json Latest spring boot spring rest

Spring REST error handling Example – Mkyong.com

Spring REST error handling Example - Mkyong.com

In this article we’ll show you error handling in Spring Boot REST

Methods used:

  • Spring Boot 2.1.2.RELEASE
  • Spring 5.1.4.RELEASE
  • Maven three [19659004] Java 8

] 1. / errorezet [19659008] 1.1 By default, Spring Boot offers a BasicErrorController driver / error mapping that handles all errors, and getErrorAttributes generates a JSON response with error details, HTTP status, and exception message.

"Time stamp": "2019-02-27T04: 03: 52,398 + 0000"
"Status": 500,
"error": "Internal server error"
"message":"…",
"Path": "/ path"

BasicErrorController.java

org.springframework.boot.autoconfigure.net.servlet.error package deal;

// …

@Controller
@RequestMapping ("$ server.error.path: $ error.path: / error")
Generic BasicErrorController Expands AbstractErrorController

// …

@RequestMapping
public ResponseEntity <Map > Error (HttpServletRequest Request)
Map body = getErrorAttributes (request,
isIncludeStackTrace (request, MediaType.ALL));
Httpatus standing = getStatus (request);
return new ResponseEntity <> (body, state);

Units the breakpoint in IDE in this technique, you understand how Spring Boot creates a suspected JSON error response.

2. Custom Exception

In spring, we will use @ ControllerAdvice to deal with custom-made exceptions.

2.1 Customized Exception.

BookNotFoundException.java

package deal com.mkyong.error;

Public Class BookNotFoundException Expands RuntimeException

public BookNotFoundException (lengthy id)
tremendous ("Book ID not found:" + id);

The driving force, if the guide ID shouldn’t be discovered, throws the above BookNotFoundException

BookController.java

package deal com.mkyong;

// …

@RestController
public class BookController

@Autowired
a personal BookRepository archive;

// Discovery
@GetMapping ("/ books / id")
Ebook findOne (@PathVariable Lengthy id)
restore archive.findById (id)
.orElseThrow (() -> new BookNotFoundException (s));

// …

By default, Spring Boot creates the next JSON error, http 500 error.

Terminal

curl localhost: 8080 / books / 5

"Time stamp": "2019-02-27T04: 03: 52,398 + 0000"
"Status": 500,
"error": "Internal server error"
"message": "Book ID not found: 5",
"Path": "/ Books / 5"

2.2 If a e-book can’t be discovered, it ought to reset the 404 error as an alternative of 500, we will skip the standing code as follows:

CustomGlobalExceptionHandler.java

package deal com.mkyong.error;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.net.bind.MethodArgumentNotValidException;
import org.springframework.net.bind.annotation.ControllerAdvice;
import org.springframework.net.bind.annotation.ExceptionHandler;
import org.springframework.net.bind.annotation.RestControllerAdvice;
import org.springframework.net.context.request.WebRequest;
import org.springframework.net.servlet.mvc.technique.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Listing;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice
public class CustomGlobalExceptionHandler expands ResponseEntityExceptionHandler

// Let the SpringErrorController handle the exception, we simply skip the status code
@ExceptionHandler (BookNotFoundException.class)
public void springHandleNotFound (HttpServletResponse response) throws IOException
response.sendError (Httpatus.NOT_FOUND.value ());

// …

2.3 It Now Returns 404

Terminal

curl localhost: 8080 / books / 5

"Time Stamp": "2019-02-27T04: 21: 17,740 + 0000"
"Status": 404,
"no error found",
"message": "Book ID not found: 5",
"Path": "/ Books / 5"

2.4 In addition, we will customize the complete JSON error response:

CustomErrorResponse.java

package deal com.mkyong.error;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.time.LocalDateTime;

public class CustomErrorResponse

@JsonFormat (format = JsonFormat.Shape.STRING, sample = "yyyy-MM-dd hh: mm: ss")
personal LocalDateTime timestamp;
personal int mode;
personal character error;

//…lähettäjät

CustomGlobalExceptionHandler.java

package deal com.mkyong.error;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.net.bind.annotation.ControllerAdvice;
import org.springframework.net.bind.annotation.ExceptionHandler;
import org.springframework.net.context.request.WebRequest;
import org.springframework.net.servlet.mvc.technique.annotation.ResponseEntityExceptionHandler;

import java.time.LocalDateTime;

@ControllerAdvice
public class CustomGlobalExceptionHandler expands ResponseEntityExceptionHandler

@ExceptionHandler (BookNotFoundException.class)
public ResponseEntity customHandleNotFound (exception ex, WebRequest request)

CustomErrorResponse Errors = New CustomErrorResponse ();
errors.setTimestamp (LocalDateTime.now ());
errors.setError (ex.getMessage ());
errors.setStatus (HttpStatus.NOT_FOUND.worth ());

return new ResponseEntity <> (errors, HttpStatus.NOT_FOUND);

// …

Terminal

curl localhost: 8080 / books / 5

"time stamp": "2019-02-27 12:40:45"
"Status": 404,
"error": "Book ID not found: 5"

3. JSR 303 Validation Error

3.1 For Spring @ Validation Errors it throws a handleMethodArgumentNotValid

CustomGlobalExceptionHandler.java

package deal com.mkyong.error;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.net.bind.MethodArgumentNotValidException;
import org.springframework.net.bind.annotation.ControllerAdvice;
import org.springframework.net.bind.annotation.ExceptionHandler;
import org.springframework.net.context.request.WebRequest;
import org.springframework.net.servlet.mvc.technique.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Record;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice
public class CustomGlobalExceptionHandler expands ResponseEntityExceptionHandler

// …

// @Validate to validate path variables and request parameters
@ExceptionHandler (ConstraintViolationException.class)
public void constraintViolationException (HttpServletResponse response) throws IOException
response.sendError (HttpStatus.BAD_REQUEST.value ());

// @ Valid error message
@Bypass
protected by ResponseEntity
handleMethodArgumentNotValid (MethodArgumentNotValidException ex,
HttpHeaders-headers,
HttpStatus Mode, WebRequest Request)

Map physique = new LinkedHashMap <> ();
physique.put ("timestamp", new date ());
body.put ("status", status.worth ());

// Get all of the fields
Record errors = ex.getBindingResult ()
.getFieldErrors ()
.stream ()
.map (x -> x.getDefaultMessage ())
Acquire (Collectors.toList ());

physique.put ("errors", errors);

return new ResponseEntity <> (frame, headers, status);

4. ResponseEntityExceptionHandler

4.1 If we aren’t positive what the exception for the spring return was, set this technique as a breakpoint for error correction

ResponseEntityExceptionHandler.java

package deal org.springframework.net.servlet.mvc.technique.annotation;

// …
public summary class ResponseEntityExceptionHandler

@ExceptionHandler (
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
HttpMediaTypeNotAcceptableException.class,
MissingPathVariableException.class,
MissingServletRequestParameterException.class,
ServletRequestBindingException.class,
ConversionNotSupportedException.class,
TypeMismatchException.class,
HttpMessageNotReadableException.class,
HttpMessageNotWritableException.class,
MethodArgumentNotValidException.class,
MissingServletRequestPartException.class,
BindException.class,
NoHandlerFoundException.class,
AsyncRequestTimeoutException.class
)
@Nullable
public ultimate ResponseEntity handleException (exception ex, WebRequest request) casts an exception
HttpHeaders headers = new HttpHeaders ();

if (e.g. HttpRequestMethodNotSupportedException)
HttpStatus status = HttpStatus.METHOD_NOT_ALLOWED;
return handleHttpRequestMethodNotSupported ((HttpRequestMethodNotSupportedException) ex, headers, standing, request);

otherwise, if (e.g., HttpMediaTypeNotSupportedException)
HttpStatus standing = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
return handleHttpMediaTypeNotSupported ((HttpMediaTypeNotSupportedException) ex, headers, status, request);

// …

// …

5. DefaultErrorAttributes

5.1 To override the default JSON error for all exceptions, create a bean and broaden DefaultErrorAttributes

CustomErrorAttributes.java

package deal com.mkyong.error;

import org.springframework.boot.net.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Element;
import org.springframework.net.context.request.WebRequest;

import java.textual content.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Element
public class CustomErrorAttributes extends DefaultErrorAttributes

personal Static ultimate DateFormat dateFormat = new SimpleDateFormat ("yyyy / MM / dd HH: mm: ss");

@Bypass
public map getErrorAttributes (WebRequest webRequest, boolean includeStackTrace)

// Let the spring deal first, we'll change later 🙂
Map errorAttributes = super.getErrorAttributes (webRequest, includeStackTrace);

// format and replace timestamp
Object Time Stamp = errorAttributes.get ("time stamp");
if (time stamp == null)
errorAttributes.put ("time stamp", dateFormat.format (new date ()));
different
errorAttributes.put ("time stamp", dateFormat.format ((date) timestamp));

// add a brand new key
errorAttributes.put ("version", "1.2");

return error values;

Now date is formatted and new subject model added to JSON error response

curl localhost: 8080 / books / 5

"time stamp": "2019/02/27 13:34:24",
"Status": 404,
"no error found",
"message": "Book ID not found: 5",
"Path": "/ Books / 5"
"Version": "1.2"

curl localhost: 8080 / abc

"time stamp": "2019/02/27 13:35:10",
"Status": 404,
"no error found",
"message": "No messages available",
"Path": "/ ABC",
"Version": "1.2"

Accomplished

Download Supply

References