SpringBoot special study Part17: SpringBoot custom custom error pages and JSON response data

Sometimes there have been some error page and error page will appear
but SpringBoot a little ugly default error page can be customized to change it

When accessed using a browser displays the error page
Here Insert Picture Description
when using other ways to access the returns JSON data
Here Insert Picture Description
thus divided into two parts to customize how to modify the record
first and foremost principle

principle:

SpringBoot ErrorMvcAutoConfiguration class to handle exceptions in
which the vessel is to add four more important classes:

  • . 1 , DefaultErrorAttributes
    can obtain information on the page by a corresponding Key:
    timestamp: timestamp
    status: status code
    error: error
    exception: Exception Objects
    message: exception message
    errors: data parity error (JSR303)
  • 2 , BasicErrorController
    bottom:
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
    ...(省略)
}

The default handling / error Request

  • . 3 , ErrorPageCustomizer
    bottom:
@Value("${error.path:/error}")
private String path = "/error";

When a system error will come / error process the request

  • 4 , DefaultErrorViewResolver
    designated Springboot default error page path
    if the template engine parses the page address you use to parse template engine and return to the address specified view
    if the find can not be resolved in the corresponding static resource folder page

Internal execution process is as follows:
First, a system error 4xx 5xx, or the like appears, and then ErrorPageCustomizer take effect according to the internal rules customized error response
and to / error request is BasicErrorController processed Although there are two methods which are processed is / error requests
but it will according to the page or other page html page is then performed in two different ways to generate the two different data
is value of the Accept header in the browser will be with text / html (distinguishing method other clients no)
and then call DefaultErrorViewResolver parser to get ModelAndView which contains the error message

The default Springboot can find a error / [status code] page (example: error / 404.html)
If the template engine can parse the address of the page template engine to parse the returned ModelAndView return to the address specified view
, if not resolve it in a static resource folder under find the corresponding error / [status code] page

A custom error page

1, if the template engine

The error page named: status code .html
placed under error template engine package next package (not have to create your own default)
Example: error/404.html
Here Insert Picture Description
When an error occurs this status code will jump to the page
error page also named 4xx or 5xx which represents the wrong that number will jump to the beginning of the page
page when exist if an exact match is an exact match with the first page

Then you can get directly on the foreground page
example:

<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>

The remaining parameters are so available in the DefaultErrorAttributes
Here Insert Picture Description

2. If there is no template engine

When the template engine can not find the file html error page
will go resources under static resource static package under the package to find

Note: Even if the package is placed under static resources also needs to have error packet
that is / resources / static / error / status codes .html
otherwise there will still the original default error page not equipped with a sample configuration

If the above two paths are not configured will come SpringBoot default error page


Second, the custom error message JSON data

The default return anomaly is this:
Here Insert Picture Description
shows the default information
can be displayed for a specified custom message
just write an exception handler:

@ControllerAdvice
public class MyExceptionHandler {

    // 只要出现异常 SpringMVC即调用该方法
    // ExceptionHandler指定要处理的异常
    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map handleException(Exception e)
    {
        Map<String,Object> map=new HashMap<>();
        map.put("code","user not exist");
        map.put("message",e.getMessage());
        return map;
    }
}

Such a designation information is returned
Here Insert Picture Description
the same way on the page
Here Insert Picture Description
the page mode and the other clients are returned JSON data
no adaptation effect

You can also implement an adaptive effect
that is displayed is a web page visits and not JSON data

Pt2 adaptive effect:

Browser and client data returned by different

Background needs to be forwarded to the map on the key / error:

@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request)
{
    Map<String,Object> map=new HashMap<>();
    // 传入错误状态码 否则默认200
    // 注:key必须为javax.servlet.error.status_code
    request.setAttribute("javax.servlet.error.status_code",500);

    map.put("code","user not exist");
    map.put("message",e.getMessage());

    // 转发到/error 然后让底层的BasicErrorController进行自适应处理
    return "forward:/error";
}

Reception Thymeleaf template values:

<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>
<h2>error:[[${error}]]</h2>
<h2>message:[[${message}]]</h2>
<h2>extra:[[${extra}]]</h2>

Display:
Here Insert Picture Description
Here Insert Picture Description
So these data are key to default
, how to customize the data carries

Pt3 custom data:

  • A method for the preparation of a ErrorController AbstractErrorController class or subclass into a container
  • Second method, impression data page or JSON return data is obtained by the errorAttributes.getErrorAttributes
    container DefaultErrorAttributes.getErrorAttributes () The default data processing
    therefore rewrite getErrorAttributes()method can

DefaultErrorAttributes inherited classes:

// 添加到容器中
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
        // 添加上错误信息中要增加的字段
        map.put("company","zjitc");

        // 异常处理器携带的数据
        // 0代表从Request域中获取
        Object extra = webRequest.getAttribute("extra", 0);
        map.put("extra",extra);
        // 该返回值 即为 页面和json可获取的所有错误信息字段
        return map;
    }
}

Abnormal catcher:

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request)
    {
        Map<String,Object> map=new HashMap<>();
        // 传入错误状态码 否则默认200
        // 注:key必须为javax.servlet.error.status_code
        request.setAttribute("javax.servlet.error.status_code",500);

        map.put("code","user not exist");
        map.put("message",e.getMessage());

        // 存放自定义的显示信息 然后存到Request域里 这样 底层的错误信息处理器就能接受到了
        request.setAttribute("extra",map);

        // 转发到/error 然后让底层的BasicErrorController进行自适应处理
        return "forward:/error";
    }
}

Reception Thymeleaf template values:

<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>
<h2>error:[[${error}]]</h2>
<h2>message:[[${message}]]</h2>
<h2>extra:[[${extra}]]</h2>

Effect:
Here Insert Picture Description
Here Insert Picture Description
ultimately the adaptive effect
customized content needs to return


Published 174 original articles · won praise 5 · Views 240,000 +

Guess you like

Origin blog.csdn.net/Piconjo/article/details/104967163