Search code examples
spring-mvcspring-rest

How do I use ResponseEntity to return simple error message from my REST call?


I have a web app written in Java and Spring MVC.

There's a REST web service, when it works I get back the Employee in JSON format.

But where there's an error, I get back a big JSON string that contains an HTML error page that doesn't include my sErrorMsg string (a sample of the error JSON is included below).

QUESTION: How do I get the error response to be a simple JSON string with my error message in it?

@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;
}

Error 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 ... */ }

Solution

  • I was causing the problem myself with an errant throw x that was here ...

       } catch (Exception x) {
         sErrorMsg = "Error getting employee; "+x.getMessage();
         throw x; // <<-- errant line here was causing the problem
       }
    

    I removed the throw x; and it all works fine.