通过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

猜你喜欢

转载自www.cnblogs.com/hustdc/p/10246299.html