zoukankan      html  css  js  c++  java
  • springboot

    使用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
    	at 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"
    }

  • 相关阅读:
    CSS躬行记(9)——网格布局
    CSS躬行记(8)——裁剪和遮罩
    CSS躬行记(7)——合成
    CentOS 系统目录解析
    Linux 命令快捷键
    秒的精确度
    Oracle和mysql中装逼dual表的用途介绍
    mysql 的mgr集群
    ansible笔记
    cygwin
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/11897740.html
Copyright © 2011-2022 走看看