springboot - 返回JSON error 从自定义的 ErrorController

使用AbstractErrorController(是ErrorController的实现),返回json error。

1、概览

 

 

2、基于《springboot - 映射 /error 到自定义且实现了ErrorController的Controller》,仅修改MyCustomErrorController如下:

import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @author www.gomepay.com
 * @date 2019/11/18
 */
@Controller
public class MyCustomErrorController extends AbstractErrorController {
    public MyCustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }
    @RequestMapping(value = "/error", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> handleError(HttpServletRequest request) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(request, true);
        return errorAttributes;
    }
    @Override
    public String getErrorPath() {
        return "/error";
    }
}

3、执行

1)、http://localhost:8080/

返回:

{
    "timestamp": "2019-11-20T06:43:37.244+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "test exception",
    "trace": "java.lang.RuntimeException: test exception\r\n\tat com.ebc.controller.MyController.handler(MyController.java:15)......",
    "path": "/"
}

2)、http://localhost:8080/other

{
    "timestamp": "2019-11-20T06:44:25.872+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/other"
}

 

 

posted @ 2019-11-20 14:49  遥远2  阅读(1335)  评论(0编辑  收藏  举报