SpringBoot Learning - Global Exception Handling Settings (Return to JSON)
need
illustrate
@ControllerAdvice
This annotation is a new annotation added after spring 2.3. It is mainly used to provide assistance to some low-invasive enhancements of the common needs of Controller, and is used on the @RequestMapping annotation method.
@ExceptionHandler
This annotation is an annotation used with @ExceptionHandler. It is a custom error handler. You can assemble the json string by yourself and return to the page.
Code
Create a global exception handling class as follows:
If different exceptions have different operations to implement, you only need to change the value of @ExceptionHandler's value to be different. Multiple different exceptions can be handled at the same time, but the inclusion state cannot occur.
import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;@ControllerAdvice@ResponseBodypublic class GlobalExceptionHandler { /** * All exceptions reported errors* @param request * @param exception * @return * @throws Exception */ @ExceptionHandler(value=Exception.class) public String allExceptionHandler(HttpServletRequest request, Exception exception) throws Exception { exception.printStackTrace(); System.out.println("I reported an error: "+exception.getLocalizedMessage()); System.out.println("I reported an error: "+exception.getCause()); System.out.println("I reported an error: "+exception.getSuppressed()); System.out.println("I reported an error: "+exception.getMessage()); System.out.println("I reported an error: "+exception.getStackTrace()); return "Server exception, please contact the administrator!"; } }Simulate an exception throwing class. The following example is to throw a null pointer exception and the denominator is not an exception
import org.springframework.steretype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/exceptionTest")@ResponseBodypublic class ExceptionTest { @RequestMapping("/test") public String test(){ Message msg = null; msg.toString(); createException(); return "I am normal"; } private void createException(){ int i = 5/0; }}Start Springboot, execution results
Because the returned string, you can also use the json tool class to encapsulate it and return a json string
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.