search
HomeJavajavaTutorialDetailed explanation of Spring Boot unified exception handling example code

When we are doing web applications, it is very common for errors to occur during request processing. At this time, unified exception handling is needed. This article mainly introduces to you the relevant information on how Spring Boot implements unified exception handling. Friends in need can refer to it. Let’s take a look together.

Spring Boot has error mapping by default, but this error page is not very user-friendly.

Unified exception handling

Define a class for unified exception handling by using @ControllerAdvice instead of defining it one by one in each Controller.

@ExceptionHandler is used to define the function type that the function targets, and finally maps the Exception object and request URL to the URL.

@ControllerAdvice
class ExceptionTranslator {
 public static final String DEFAULT_ERROR_VIEW = "error";
 @ExceptionHandler(value = Exception.class)
 public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
  ModelAndView mav = new ModelAndView();
  mav.addObject("exception", e);
  mav.addObject("url", req.getRequestURL());
  mav.setViewName(DEFAULT_ERROR_VIEW);
  return mav;
 }
}

Implement error.html page display

Create error.html in the templates directory.

For example:

<!DOCTYPE html> 
<html> 
<head lang="en"> 
 <meta charset="UTF-8" />
 <title>统一异常处理</title>
</head> 
<body> 
 <h1 id="Error-nbsp-Handler">Error Handler</h1>
 <p th:text="${url}"></p>
 <p th:text="${exception.message}"></p>
</body> 
</html>

Return using Json format

Just add in @ Adding @ResponseBody after ExceptionHandler can convert the content of the processing function return into JSON format

Create a JSON return object, such as:

public class ErrorDTO implements Serializable {
 private static final long serialVersionUID = 1L;
 private final String message;
 private final String description;
 private List<FieldErrorDTO> fieldErrors;
 //getter和setter省略
}

Exception handling can be added for the specified Exception

@ExceptionHandler(ConcurrencyFailureException.class)
 @ResponseStatus(HttpStatus.CONFLICT)
 @ResponseBody
 public ErrorDTO processConcurencyError(ConcurrencyFailureException ex) {
  return new ErrorDTO(ErrorConstants.ERR_CONCURRENCY_FAILURE);
 }

ErrorConstants.ERR_CONCURRENCY_FAILURE is an exception message defined.

Summarize

The above is the detailed content of Detailed explanation of Spring Boot unified exception handling example code. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools