springboot ErrorController


在编写springboot项目的时候,后端操作经常会抛出异常,而这些异常是前端无法显示的,所以我们还需切换到后端命令行才能看到具体的错误细节,非常麻烦,尤其是将项目部署到服务器上的时候,未解决这个问题,我们可以通过实现ErrorController接口,来在前端显示报错信息。

CommonErrorController

代码:

package com.example.commonerror.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class CommonErrorController implements ErrorController {
    
    

    @Autowired
    private ErrorAttributes errorAttributes;

    /**
     * 默认错误
     */
    private static final String path_default = "/error";

    @Override
    public String getErrorPath() {
    
    
        return path_default;
    }

    /**
     * JSON格式错误信息
     */
    @RequestMapping(value = path_default,  produces = {
    
    MediaType.APPLICATION_JSON_VALUE})
    public String error(HttpServletRequest request, WebRequest webRequest) {
    
    
        Map<String, Object> body = this.errorAttributes.getErrorAttributes(webRequest, true);
        return body.toString();
    }

}

测试

测试代码

package com.example.commonerror.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    
    @GetMapping("/test")
    public String test(){
    
    
        return "test";
    }

    @GetMapping("/test1")
    public String test1(){
    
    
        throw new RuntimeException("抛出异常");
    }
}

测试结果

不报错的执行

在这里插入图片描述

报错的执行

在这里插入图片描述

源代码

项目源码

猜你喜欢

转载自blog.csdn.net/hzhxxxx/article/details/108976735