首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用ResponseEntity从REST调用返回简单的错误消息?

如何使用ResponseEntity从REST调用返回简单的错误消息?
EN

Stack Overflow用户
提问于 2020-06-11 04:44:30
回答 1查看 2.8K关注 0票数 0

我有一个用Java和Spring MVC编写的web应用程序。

有一个REST web服务,当它工作时,我会得到JSON格式的Employee

但是在出现错误的地方,我会得到一个很大的JSON字符串,其中包含一个不包含我的sErrorMsg字符串的HTML error页面(下面包含了一个error JSON的示例)。

问:如何将错误响应转换为包含错误消息的简单JSON字符串?

代码语言:javascript
运行
复制
@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 ...

代码语言:javascript
运行
复制
{"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 ... */ }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-11 04:51:16

我自己造成了这个问题,因为这里有一个错误的throw x

代码语言:javascript
运行
复制
   } catch (Exception x) {
     sErrorMsg = "Error getting employee; "+x.getMessage();
     throw x; // <<-- errant line here was causing the problem
   }

我移除了throw x;,一切都很正常。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62312788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档