通過spring boot提供restful api
1 將返回設置為produces =
"application/json"
返回給客戶端json格式的response。
2 對各種異常的處理
各種異常如何返回給客戶端?
各種異常通過ResponseEntity返回給客戶端。
3 一種通用的處理方式
3.1 定義一個Exception對象
public class UserNotFountException extends RuntimeException{
private String userId;
public UserNotFountException(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
3.2 定義對應的ExceptionHandler
@ExceptionHandler(UserNotFountException.class)
public ResponseEntity<Error> UserNotFound(UserNotFountException e){
String userId = e.getUserId();
Error error = new Error(4 , "User ("+userId+") not found");
return new ResponseEntity<Error>(error,HttpStatus.NOT_FOUND);
}
3.3 有異常的時候直接返回異常
@RequestMapping(value = "/{id}",method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<User> getUserById (@PathVariable("id") String id){
//初始化用戶信息
initUserInfo();
User result = users.get(id);
HttpStatus status = result != null ? HttpStatus.OK : HttpStatus.NOT_FOUND;
if(result == null){
throw new UserNotFountException(id);
}
return new ResponseEntity<User>(result,status);
}
參考資料:
https://blog.csdn.net/github_34889651/article/details/53705306
通過spring boot提供restful api