3

Using latest Spring Boot as of May 2018. I've created a 404 response like this.

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {

    private final int errorId;

    public NotFoundException(String errorMsg) {
        super("-1," + errorMsg);
        this.errorId = -1;
    }

    public NotFoundException(int errorId, String errorMsg) {
        super(errorId + "," + errorMsg);
        this.errorId = errorId;
    }


    public int getErrorId() {
        return errorId;
    }
}

The annotation @ResponseStatus(HttpStatus.NOT_FOUND) makes my NotFoundException appear like a 404 reponse like this

{
    "timestamp":1527751944754,
    "status":404,
    "error":"Not Found",
    "exception":"com.myapp.exception.NotFoundException",
    "message":"1000,Could not find data for owner: 1234","path":"/resource/owner/1234"
}

I hoped that property "getErrorId" would appear in the response automatically, like this

{
    "timestamp":1527751944754,
    "status":404,
    "error":"Not Found",
    "exception":"com.myapp.exception.NotFoundException",
    "message":"Could not find data for owner: 1234","path":"/resource/owner/1234",
    "errorId": 1000
}

Is the a simply way (like an annotiation to the getErrorId method) of having the property "errorId" in the response?

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
Vering
  • 907
  • 9
  • 19

2 Answers2

2

You use @ControllerAdvice and @ExceptionHanlder in Spring. that is exception controller. In fact, you will make custom exception controller and define exception.

This is sample code for you :

@ControllerAdvice("your.package")
public class CommonExceptionHandler {

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public @ResponseBody ResponseEntity<?> setNotFoundException(Exception exception) throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();

        // this is sample map. you will make your custom model and you use exception parameter.
        Map<String, String> map = new HashMap<String, String>();
        map.put("timestamp", String.valueOf(new Date().getTime()));
        map.put("status", HttpStatus.NOT_FOUND.toString());
        map.put("error", "Not Found");
        map.put("exception", exception.getMessage());
        map.put("message", "Could not find data for owner: 1234");
        map.put("path", "/resource/owner/1234");
        map.put("errorId", "1000");

        String json = mapper.writeValueAsString(map);

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(json);
    }

}
0gam
  • 1,343
  • 1
  • 9
  • 21
  • Thanks a lot - will try this out. I think I could cast the Exception to my NotFoundException and then extract the fields one-by-one. – Vering May 31 '18 at 09:40
0

what ever Byeon0gam told everything is fine, here i am going to show another way means little bit of difference in maintaining code.

We know already , we can handle exceptions in spring-rest by 4 ways: 1. Using ResponseEntity Class. 2. Using @ResponseStatus Annotation. 3. Using @ExceptionHandler() Annotation. 4. Return Error Representation instead of default HTML error Page.

By using Those we can handle Exceptions at Method or Class level only. But, if you want to handle Globally means throughout application , please follow below steps.

Handling Global Exception: To Handle all Exceptions in our applications , First we need to create a class, after we need to use @ControllerAdvice Annotation on top of a class. In that class body , we can handle the exceptions raised in our application. In that Class , we will create Exception handling methods , on top of every method we will use @ExceptionHandler() annotation for navigating Exceptions and for Handling . If any exception raises in our application , based on @ExceptionHandler(“argument”) annotation argument the exception hadling method will be invoked and remaining handling code will be excuted.

@ControllerAdvice 
public class SpringRestGlobalExceptionHandler {
@ExceptionHandler(Exception.class) 
  public ResponseEntity<?> exceptionHandler(HttpServletRequest req, Exception e) 
  {
    JSONObject obj =new JSONObject();
    obj.put("msgTxt","Unknown Server Error, Please Contact Admin." );
    obj.put("reqUrl", req.getRequestURI());
    obj.put("stackTrace", e.toString());
    obj.put("isErrorFlag", true);
    obj.put("httpStatusCode", HttpStatus.OK.value());
    gstcDaoi.saveExceptionOrErrorLog(prepareTGstcExceptionOrErrorLogObject(obj));
     e.printStackTrace();

    return new ResponseEntity<>(obj, HttpStatus.OK);
  }