404异常中的java Spring自定义消息
我的控制器中有一个方法,如下所示:
@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.POST)
public @ResponseBody
VideoStatus setVideoData(
@PathVariable(VideoSvcApi.ID_PARAMETER) long id,
@RequestParam(value = VideoSvcApi.DATA_PARAMETER) MultipartFile videoData,
HttpServletResponse response) {
Video video = null;
for (Video v : videos) {
if (v.getId() == id) {
video = v;
break;
}
}
if (video == null) {
throw new VideoNotFoundException(id);
} else {
try {
videoFileManager.saveVideoData(video,
videoData.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
自定义异常如下所示:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
private class VideoNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public VideoNotFoundException(long id) {
super("Video with id " + id + " not found");
}
}
当我用一个不存在的id点击某个路径时,响应如下:
{
"timestamp":1407263672355,
"error":"Not Found",
"status":404,
"message":""
}
我的问题是。。。如何在响应中设置自定义消息,但保留json结构的其余部分
我知道我可以在注释中使用“reason”属性(在自定义异常中),但这样做我总是会返回相同的消息,我想显示一条消息,比如:“找不到id为X的视频”
谢谢
# 1 楼答案
这就是我最后要做的
现在我的回答是这样的: