0

I have the following method in my service layer.

public void delete(int candidateId) {
    candidateRepository.delete(candidateId);
}

Pretty basic, now this method is used by the web layer which RESTful architecure is applied. The URL that will trigger this method is:

DELETE    /candidates/{id}

How should I deal with wrong ids given by the clients that use the REST API in the service layer? I know the HTTP response would be 4xx but how should I communicate that the id is invalid between the service and web layer?

Should I use a unchecked exception since this is a condition that my application is unable to recover from? The fault barrier (Spring exception handler) will deal with it.

Or should this be a checked exception since it is possible that clients give wrong ids?

I am using the latest Spring technology if that matter

LuckyLuke
  • 47,771
  • 85
  • 270
  • 434

2 Answers2

0

If it is possible that clients give wrong ids, then they will give wrong ids. And this is a condition that your application should be able to recover from.

I would return a checked exception for this. But introducing a checked exceptions can sometimes mean changes throughout different layers of the application, because, for example, the signatures of many methods would need to be changed to add the "throws" clause (breaking OCP). In case that gets overcomplicated some people (like in Robert C. Martin's "Clean Code") recommend using unchecked exceptions. I would say it's up to you what to return as long as the exception has a meaningful description.

ovdsrn
  • 793
  • 1
  • 7
  • 24
0

Firstly, you need to decide how your REST API will handle exceptions. There are multiple, equally valid solutions to this.

When designing an API, you pretty much have to assume that whatever can go wrong, will go wrong. Client applications will pass incorrect parameters, use incorrect formats, etc.; your application should expect this, and handle it gracefully.

Using exceptions to communicate business logic is not particularly readable, and may have performance implications. It really doesn't scale beyond very simple cases - imagine that the business logic for "delete" might need to include failures for "record not found", "record has dependent relationships", "record protected", "record archived" etc.

Instead, I would design the application to pass explicit status information back and forth, and translate this into whatever RESTful error handling you use.

Community
  • 1
  • 1
Neville Kuyt
  • 29,247
  • 1
  • 37
  • 52
  • Would you may give an example of the status information you will pass back and forth? – LuckyLuke Nov 08 '14 at 11:53
  • If I have a `DeletionFailedException (checked)` that has a constructor that takes a list of the reasons it may not be that bad. Exceptions is the way you communicate alternative returns of method so... – LuckyLuke Nov 08 '14 at 11:57