码迷,mamicode.com
首页 > 编程语言 > 详细

通过spring boot提供restful api

时间:2019-01-09 20:28:43      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:art   map   exce   details   ==   article   一个   runtime   定义   

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

标签:art   map   exce   details   ==   article   一个   runtime   定义   

原文地址:https://www.cnblogs.com/hustdc/p/10246299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!