SpringBoot定義了默認處理異常的機制,簡單的說就是APP客戶端訪問默認返回json,瀏覽器訪問默認返回錯誤頁面。使用Restful風格開發,我們往往習慣處理異常時,返回json串。下面說說怎樣使瀏覽器訪問,默認返回json串。
1、默認跳轉頁面
@RestController @RequestMapping("/user") public class UserController {
@GetMapping("/exception/{id:\\d+}") public User getUserInfo(@PathVariable String id){ throw new RuntimeException("user not exist"); } }
瀏覽器測試:http://localhost/user/exception/1,跳轉到錯誤頁面,顯示錯誤信息 user not exist
2、自定義返回json格式數據
自定義異常類UserNotExistException.java
public class UserNotExistException extends RuntimeException { private static final long serialVersionUID = -6112780192479692859L; private String id; public UserNotExistException(String id) { super("user not exist"); this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
自定義異常處理類ControllerExceptionHandler.java
@ControllerAdvice public class ControllerExceptionHandler { @ExceptionHandler(UserNotExistException.class) @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Map<String,Object> handlerUserNotExistException(UserNotExistException userNotExistException){ Map<String,Object> map=new HashMap<>(); map.put("id", userNotExistException.getId()); map.put("message", userNotExistException.getMessage()); return map; } }
修改UserController.java中getUserInfo方法
@GetMapping("/exception/{id:\\d+}") public User getUserInfo(@PathVariable String id){ throw new UserNotExistException(id); }
瀏覽器測試:http://localhost/user/exception/1,返回json格式數據,顯示錯誤信息
說明:
1)如果getUserInfo方法中拋出RuntimeException,依然跳轉頁面,因為在異常處理類中指定的異常類型是UserNotExistException。
2)如果異常處理類中指定的異常類型是Exception,那么getUserInfo方法中拋出任何異常都會返回json格式數據。
3)業務類中拋出的是異常處理類定義的類型或是定義類型的子類型,才會返回json格式數據。
更多異常處理請看我的文章:Spring Boot之異常處理的兩種方式、Spring MVC之處理異常的兩種方式及優先級