首页 > 解决方案 > 如何从否则返回集合的方法返回错误消息

问题描述

这更像是一个概念性的东西。我的方法应该返回一个Conferences. 但是如果有错误,我只希望它发送一个字符串响应或者可能是一个 JSON 响应,如{err: 'Some error'}.Offcourse 以下方法会为这一行抛出编译器错误 - return e.getMessage();。如何做到这一点?

@RequestMapping(value = "/api/allconf", method = RequestMethod.GET)
public List<Conferences> getAllConf(@RequestBody Conferences conf) {
    List<Conferences> allConf = new ArrayList<Conferences>();
    try {
        allConf.addAll(confRepository.findAll());
    } catch(Exception e){
        return e.getMessage();
    }
    return allConf;
}

标签: javaspringspring-bootcollections

解决方案


e.getMessage() 返回一个字符串,你的方法是一个会议列表,使用一个新的通用响应类,如

public class Response {

   private Object content;

   private String error;

   // getters and setters

}

并改变你的方法

@RequestMapping(value = "/api/allconf", method = RequestMethod.GET)
    public Response getAllConf(@RequestBody Conferences conf) {

        Response resp = new Response();
        List<Conferences> allConf = new ArrayList<Conferences>();
        try{
            allConf.addAll(confRepository.findAll());
            resp.setContent(allConf);
        }catch(Exception e){
           resp.setError(e.getMessage());
        }
        return resp;
    }

推荐阅读