我的控制器中有一个方法,如下所示:
@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不是发现“
谢谢!
答案 0 :(得分:1)
这就是我最终做的......
private class VideoNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public VideoNotFoundException(long id) {
super("Video with id " + id + " not found");
}
}
@SuppressWarnings("unused")
private class VideoNotFoundExceptionMessage {
private long timestamp;
private String error;
private int status;
private String exception;
private String message;
public VideoNotFoundExceptionMessage() {
// constructor
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@ExceptionHandler(VideoNotFoundException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
private VideoNotFoundExceptionMessage VideoNotFoundExceptionHandler(VideoNotFoundException e) {
e.printStackTrace();
VideoNotFoundExceptionMessage message = new VideoNotFoundExceptionMessage();
message.setTimestamp(new Date().getTime());
message.setError("Not Found");
message.setStatus(404);
message.setException(e.getClass().getCanonicalName());
message.setMessage(e.getMessage());
return message;
}
现在我的回答如下:
{
"timestamp":1407271330822,
"error":"Not Found",
"status":404,
"exception":"org.magnum.dataup.VideoController.VideoNotFoundException",
"message":"Video with id 2 not found"
}
答案 1 :(得分:0)
ResponseStatus具有您可以使用的reason
属性。