java - 如何从否则返回集合的方法返回错误消息
问题描述
这更像是一个概念性的东西。我的方法应该返回一个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;
}
解决方案
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;
}
推荐阅读
- jquery - 为什么标头访问控制允许来源不起作用?
- google-apps-script - 如何正确组合 2 个脚本,所以两者都是 onEdit?
- git - Upsource:合并评论在评论摘要中不显示任何内容
- python - AttributeError:模块“discord.client”没有属性“事件”
- python - 将表格刮到excel文件
- python - 对 pandas 数据框进行窗口化操作,以列出与前 n 个条目的欧几里得距离
- java - 如何使用 readAllBytes 将文件中的字节读入单个字符串?
- android - 如何从 Android Studio 中的目录访问模块内的类?
- php - Wordpress wp-cron.php 执行不起作用
- node.js - 使用 dio 错误从 Flutter 获取到节点 js 的请求