简体   繁体   中英

Throwing exception for missing id in REST-API

I am creating a web service API following RESTful principles. In the service layer I have a method named:

/**
 * @param answerId Id of the answer that will be deleted.
 */
void deleteAnswer(int answerId);

As you would expect this will delete the answer if the id of the answer is found in the system. Now, my question is:

Having this endpoint in the webservice:

HTTP DELETE /my-context/answers/{answerId}

the users of the API is able to add whatever id they want. They shouldn't, but they are able to. Because of that I want to throw an IllegalArgumentException from the service layer that I resolve HTTP message (Spring Web takes care of this). My other option would be to change the return type of the deleteAnswer method in the service layer so it returns true/false . What do you think?

If you return true false that means you are returning HTTP 200. While you should return 404. Spring has exception handler controller. You can throw your custom exception and define a exception handler which will send 404 with proper error message.

Returning an exception means that's an error to call your mehod like that. Returning true/false means that it's legal to call your service api like that. Because you said "they shouldn't" I would go for exception.

I would rather use my own exception class that could be handled more cleanly than IllegalArgumentException.

Your web service should signal an error by specifying an appropriate status code, such as 400 or 404.
Your web service signature will then be:

ResponseEntity<Void> deleteAnswer(@PathVariable("answerId") int answerId);

You can throw an exception from the service layer, it's absolutely fine.
Then you could catch it in your 'deleteAnswer' method and return an appropriate status code.

Alternatively (and better), you can handle all the exceptions from all controllers in one place using

@ControllerAdvice class YourExceptionResolver {
     @ExceptionHandler
     public ResponseEntity<String> defaultErrorHandler(HttpServletRequest req, Exception e) {
         //return status code 400, 404, or 500 based on the exception 
         //with String containing the error message
     }
 }

If you use @ControllerAdvice and exceptions from the service layer, you can keep your original signature 'void deleteAnswer(int answerId)'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM