天天看點

Spring Boot自定義錯誤處理實戰

一 代碼位置

https://gitee.com/cakin24/code/tree/master/07/Error

二 代碼

package com.example.demo.Controller;


import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
/*springboot提供了預設的錯誤映射位址error
@RequestMapping("${server.error.path:${error.path:/error}}")
@RequestMapping("/error")
上面2種寫法都可以
*/
@RequestMapping("/error")
//繼承springboot提供的ErrorController,自定義一個錯誤處理控制器
public class TestErrorController implements ErrorController {
    //一定要重寫方法,預設傳回null就可以,不然報錯,因為getErrorPath為空.
    @Override
    public String getErrorPath() {
        return null;
    }


    //一定要添加url映射,指向error
    @RequestMapping
    public Map<String, Object> handleError() {
        //用Map容器傳回資訊
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 404);
        map.put("msg", "不存在");
        return map;
    }
    /*這裡加一個能正常通路的頁面,作為比較
    因為寫在一個控制器是以它的通路路徑是
    http://localhost:8080/error/ok*/
    @RequestMapping("/ok")
    @ResponseBody
    public Map<String, Object> noError() {
        //用Map容器傳回資訊
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code ", 200);
        map.put("msg", "正常,這是測試頁面");

        return map;
    }
}
           

三 測試

1 浏覽器輸入一個不存在的URL: http://localhost:8080/

Spring Boot自定義錯誤處理實戰

2 浏覽器輸入: http://localhost:8080/error/ok

Spring Boot自定義錯誤處理實戰

繼續閱讀