【发布时间】:2020-06-10 20:44:29
【问题描述】:
我有一个用 Java 和 Spring MVC 编写的网络应用程序。
有一个 REST Web 服务,当它工作时,我会以 JSON 格式返回 Employee。
但如果出现错误,我会返回一个大的 JSON 字符串,其中包含一个不包含我的 sErrorMsg 字符串的 HTML 错误页面(下面包含错误 JSON 的示例)。
问题:如何将错误响应变成包含错误消息的简单 JSON 字符串?
@RequestMapping(value = "/json/employee/{employeeId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Employee> getEmployee(@PathVariable("employeeId") int employeeId) throws Exception {
Employee employee = null;
String sErrorMsg = "";
try {
employee = employeeService.getEmployee(employeeId);
} catch (Exception x) {
sErrorMsg = "Error getting employee; "+x.getMessage();
// UPDATE:
// throw x; <<-- errant line here was causing the problem
//
}
ResponseEntity responseEntity = null;
if (ret != null) {
ResponseEntity responseEntity = ResponseEntity.ok(employee);
} else {
responseEntity = ResponseEntity.badRequest().body(sErrorMsg);
}
return responseEntity;
}
错误 JSON ...
{"readyState":4,"responseText":"<!doctype html><html lang=\"en\"><head><title>HTTP Status 500 – Internal Server Error</title><style type=\"text/css\">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line /* the rest of the HTML which contains a length Java stack trace ... */ }
【问题讨论】:
-
我才意识到出了什么问题。在 catch 中有一个
throw x;导致了意外的行为。