Spring boot會自動產生‘whitelabel’的錯誤網頁,如果,想要客製錯誤網頁,可以加一個error.html(以Thymeleaf而言)或者,當發生錯誤或例外時,會自動呼叫這個頁面。也可以寫一個Controller來處理,以下面的範例而言,這個Controller必須implements ErrorController,而且RequestMapping要對應到/error。
package com.example.demo.controller;import org.springframework.boot.autoconfigure.web.ErrorController;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class ErrorHandleController implements ErrorController{private static final String PATH = "/error";@RequestMapping(value = PATH)public ModelAndView error() { ModelAndView model = new ModelAndView("uploadForm"); model.addObject("message","沒有選擇檔案"); return model;}@Overridepublic String getErrorPath() { return PATH;}}但是,通常會產生錯誤或例外的原因不會只有一種,所以,可以根據不同的錯誤或例外來處理。首先,要將這個Controller改為ControllerAdvice,這樣的話,Spring Boot才知道這是個有@ExceptionHandler的Controller。再來,利用@ExceptionHandler來指定要處裡哪一種Exception。
package com.example.demo.controller;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import com.example.storage.StorageException;import org.springframework.web.servlet.ModelAndView;@ControllerAdvicepublic class ErrorHandleController {// Specify name of a specific view that will be used to display the error:@ExceptionHandler(StorageException.class)public ModelAndView notFoundErrors(Exception e) { ModelAndView model = new ModelAndView("uploadForm"); model.addObject("message",e.getMessage()); return model;}}*本範例的完整內容(如:StorageException)請參考Spring FileUpload。