Springboot local and global exception handling

Local exception handling

Operation of the TestController class

(1), create an exception

If you set a variable = integer / 0, an ArithmeticException will occur Exception

Adds 0 exception point in TestController

@RequestMapping("/hello1")

Public String hello(){

// I wrote a divide-by-zero exception

Int a=1/0;


Return "hello1";

}

(2), write exception handling method

Add exception handling method in TestController

//Local exception handling

@ExceptionHandler(Exception.class)

Public String exHandler(Exception e){

/ / Determine the type of exception occurred in response to 0 exceptions to respond

If(e instanceof ArithmeticException){

Return "An exception of 0 has occurred";

}

// Unknown exception responds

Return "An unknown exception has occurred";

}

(3), test

Enter the address: http://localhost:8080/test/hello1

If the display shows: Except 0 exception, the test succeeds

Global exception Handle

(1), create a new Controller class

包名:package com.springboot.controller;

类名:TestGlobalController

package com.springboot.controller;


Import org.springframework.web.bind.annotation.RequestMapping;

Import org.springframework.web.bind.annotation.RestController;


@RestController

@RequestMapping("/test")

Public class TestGlobalController {


@RequestMapping("/hello2")

Public String hello2(){

// The exception point that I wrote myself

Int a=1/0;


Return "hello2";

}


}

(2), write global exception class

包名:com.springboot.controller.exception

类名:GlobalDefaultExceptionHandler

1.Global exception handling return string

 Package com.springboot.controller.exception;


Import org.springframework.web.bind.annotation.ControllerAdvice;

Import org.springframework.web.bind.annotation.ExceptionHandler;

Import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice

Public class GlobalDefaultExceptionHandler {


// global exception handling returns a string

@ExceptionHandler(Exception.class)

@ResponseBody

Public String exception(Exception e){

/ / Determine the type of exception occurred in response to 0 exceptions to respond

If(e instanceof ArithmeticException){

Return "global: a divide exception exception occurred";

}

// Unknown exception responds

Return "global: an unknown exception has occurred";

}

}

2.Global exception handling returns JSON

// Global exception handling returns JSON

@ExceptionHandler(Exception.class)

@ResponseBody

Public Map<String,Object> exception(Exception e){

Map<String,Object> map=new HashMap<String,Object>();


/ / Determine the type of exception occurred in response to 0 exceptions to respond

If(e instanceof ArithmeticException){

Map.put("codeNumber", "1");

Map.put("message", e.getMessage());

Return map;

}

// Unknown exception responds

Map.put("codeNumber", "0");

Map.put("message", e.getMessage());

Return map;

}

3.Global exception handling returns JSP

@@ExceptionHandler(Exception.class)

Public String exception(Exception e){


/ / Determine the type of exception occurred in response to 0 exceptions to respond

If(e instanceof ArithmeticException){

// jump to the test.jsp page

Return "test";

}

// Unknown exception responds

// jump to the test.jsp page

Return "test";

}

Note: Need to configure to support jsp

1 need to add JSP support in pom

<!-- Analysis support for JSP -->

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

<scope>provided</scope>

</dependency>

<!-- Support for JSTL -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

2You need to configure application.properties

to add the application.properties file, and then write the

# page default prefix directory to it.

Spring.mvc.view.prefix=/WEB-INF/

# response page default suffix

Spring.mvc.view.suffix=.jsp

3 Need to add jsp file

Add JSP, place it in src/main/webapp/WEB-INF directory

--------------------------------------------------------------------------------------

(3), global exception class Application scope setting

[email protected] Introduction

In spring 3.2, the @ControllerAdvice annotation can be used to define @ExceptionHandler, @InitBinder, @ModelAttribute and apply to all @RequestMapping.

Here our global exception is only applied to @ExceptionHandler

2. Set the @ControllerAdvice application scope

to set the @ControllerAdvice application scope, that is, set the application scope of the exception class

@ControllerAdvice The scope is:

1basePackages: Application in xx package

2basePackageClasses: Applies to xx class

3assignableTypes: App is added to @Controller class

4annotations: Applies in xx annotations Class or method

————————————————————

≥ simple usage example:

————————————————————

@ControllerAdvice(basePackages={"com.springboot.controller"})

only captures the exception in the com.springboot.controller package

@ControllerAdvice(basePackageClasses={TestController.class})

only catches the exception in TestController.class

@ControllerAdvice(assignableTypes={TestController.class})

only captures the testController.class Exception

@ControllerAdvice(annotations=TestException.class)

only catches classes with @TestException annotations

The above four annotations an application package, then two are used in classes, and the last one is only applied to classes with XX annotations

--------------------------------------------------------------------------------------

3. Tell the application how to write in the annotations

1, create an annotation class

Package com.springboot.annotation;


Import static java.lang.annotation.ElementType.TYPE;

Import static java.lang.annotation.RetentionPolicy.RUNTIME;


Import java.lang.annotation.Documented;

Import java.lang.annotation.Retention;

Import java.lang.annotation.Target;


// This type of Annotations will be retained by the JVM, so they can be reflected by the JVM or other use at runtime

@Retention(RUNTIME)

// The target type can be applied to the method

@Target(ElementType.TYPE)

// support for doc documentation

@Documented

Public @interface TestException {


}

---------------------------------------------------------------------------------

Note: For a brief explanation of the annotation class, please see:

---------------------------------------------------------------------------------

2, add the annotation to the TestController class

Add the @TestException annotation

// Add the TestException annotation

@TestException

@RestController

@RequestMapping("/test")

Public class TestController {


@RequestMapping("/hello1")

Public String hello(){

// I wrote a divide-by-zero exception

Int a=1/0;


Return "hello1";

}


}

3, TestController class is not annotated

@RestController

@RequestMapping("/test")

Public class TestGlobalController {


@RequestMapping("/hello2")

Public String hello(){

// I wrote a divide-by-zero exception

Int a=1/0;


Return "hello2";

}


}

4, set the exception class to only catch exceptions of classes with @TestException annotations

// Set the scope to be applied to classes with annotations of @TestException

@ControllerAdvice(annotations={TestException.class})

Public class GlobalDefaultExceptionHandler {


@ExceptionHandler(Exception.class)

@ResponseBody

Public String exceptionReturnString(Exception e){

/ / Determine the type of exception occurred in response to 0 exceptions to respond

If(e instanceof ArithmeticException){

Return "global: a divide exception exception occurred";

}

// Unknown exception responds

Return "global: an unknown exception has occurred";

}

}

5, test

Enter the address: http://localhost:8080/test/hello1

Enter the address: http://localhost:8080/test/hello2

(4 ), handling 404 error

because 404 error is not passed the controller, so it can not be handled by the above method. But SpringBoot provides a global handler by default to handle all HTTP errors and map it to /error. When an HTTP error occurs, such as a 404 error, SpringBoot's internal mechanism redirects the page to /error.

So we only need to implement a /error mapping Controller to handle it

1, create 404.jsp page

create errorpages directory under WEB-IFN, and in this directory Create a 404.jsp page

目录:

404.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Test JSP</title>

</head>

<body>

<span>A 404 error has occurred</span>

</html>

2, create a controller class for processing 404

包名:package com.springboot.controller;

类名:HttpErrorController

package com.springboot.controller;


import org.springframework.boot.autoconfigure.web.ErrorController;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;


@Controller

public class HttpErrorController implements ErrorController {


private static final String ERROR_PATH = "/error";


@RequestMapping(value=ERROR_PATH)

public String handleError(){

return "errorpage/404";

}


@Override

public String getErrorPath() {

return ERROR_PATH;

}


}

3, test

随便Entering an address test raises a 404 error

For example, enter the address: http://localhost:8080/-.-

display: