如果沒處理
tomcat默認返回500,並且包裝了返回的body,含請求時間、返回狀態碼、什麼錯誤、錯誤信息,請求路徑
controller如下
@RestController
public class MyController {
@GetMapping("/hello")
public String getString(){
int i = 1/0;
return "Hello World!";
}
}
如果標準http返回
會返回自定義的body和狀態碼
controller如下
@RestController
public class MyController {
@GetMapping("/hello")
public String getString(){
int i = 1/0;
return "Hello World!";
}
@ExceptionHandler({RuntimeException.class})
public ResponseEntity<HttpResponse>error(Exception e){
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(new HttpResponse<Object>(110,e,"報警"));
}
}
這也是一個標準返回
返回的狀態狀態碼默認500,@ResponseStatus一定要有,默認狀態碼是500
@GetMapping("/rest/v1/mockError")
public String mockError() {
int i = 1/0;
return "mockError";
}
@ExceptionHandler({RuntimeException.class})
@ResponseStatus
public String error(RuntimeException e){
return "error";
}
如果不是標準返回
那麼狀態碼是200,這個不對的
controller如下
@RestController
public class MyController {
@GetMapping("/hello")
public String getString(){
int i = 1/0;
return "Hello World!";
}
@ExceptionHandler({RuntimeException.class})
public HttpResponse error(Exception e){
return new HttpResponse<Object>(110,e,"報警");
}
}