springboot - return JSON error from ErrorController custom

Use AbstractErrorController (achieving ErrorController of), returns json error.

1, Overview

 

 

2, based on " springboot - mapping / error and to achieve a custom ErrorController of the Controller ", only MyCustomErrorController modified as follows:

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, execution

1)、http://localhost:8080/

return:

{
    "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"
}

 

 

Guess you like

Origin www.cnblogs.com/yaoyuan2/p/11897740.html