springboot报错404、500错误时返回json

介绍

根据 springboot 自定义404、500错误页 的方式二实现

实现配置类

package top.malaoshi.stdsecurity.config;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        /*报404错误时,转发到/error/404 */
        ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        /*报500错误时,转发到/error/500 */
        ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        registry.addErrorPages(e404, e500);
    }
}
  • 报404错误时,转发 到/error/404
  • 报500错误时,转发 到/error/500

创建Controller

package top.malaoshi.stdsecurity.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.malaoshi.stdsecurity.json.Result;

@RestController
@RequestMapping(value = "/error")
public class ErrorController {

    @RequestMapping(value = "/404")
    public Result error404() {
        return new Result(HttpStatus.NOT_FOUND.value(),HttpStatus.NOT_FOUND.getReasonPhrase());
    }

    @RequestMapping(value = "/500")
    public Result error500() {
        return new Result(HttpStatus.INTERNAL_SERVER_ERROR.value(),HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
    }
}

创建bean

package top.malaoshi.stdsecurity.json;

public class Result {
    private int code;
    private String msg;

    public Result(){

    }
    public Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

原文出处:/show_1EF60BXH0usd.html