如何从否则返回集合的方法中返回错误消息

时间:2019-01-07 22:35:47

标签: java spring spring-boot collections

更多是概念上的事情。我的方法应该返回Conferences的列表。但是,如果有错误,我只希望它发送String响应,或者像{err: 'Some error'}这样的JSON响应。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;
}

2 个答案:

答案 0 :(得分:1)

e.getMessage()返回一个String,并且您的方法是会议列表,请使用新的通用响应类,例如

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;
    }

答案 1 :(得分:1)

有一个选择:

最佳解决方案,它会引发异常:

@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){
        throw new IllegalArgumentException(e.getMessage()); 
    }
    return allConf;
}    

并创建一个错误处理程序来处理异常以及如何显示异常:

@ControllerAdvice
public class CustomErrorHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public void handlerIllegalArgumentException(IllegalArgumentException exception, ServletWebRequest webRequest) throws IOException {
        webRequest.getResponse().sendError(HttpStatus.BAD_REQUEST.value(), exception.getMessage());
    }
}