Chapter 4: Ticket: Handling Errors

I got this at http://localhost:5000/status:

Error Handling: The return from the api was incorrect when providing a bad id to search by

Even all tests were passed at HandlingErrorsTest.

Does someone have an idea?

Hello, I got the same message with passed tests…

I also saw this. I got passed it by improving by implementation of validIdValue() in

1 Like

I can confirm implementing validValue() makes test pass. Thanks @Michael_80468!

yes… you should add code to verify if the object id provided has a valid format or not.

Thank you for the suggestions. I had to improve the implementation of getMovie() instead of validIdValue() in

can the object id simply be checked like this?
return ObjectId.isValid(movieId);

1 Like

I think that’s the best way.

You could probably do it with a try/catch but the above is better.

In my case, checking the logs, the application also tests with malformed values, giving java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId:, capturing this exception in validIdValue (movieId), solved that problem.

1 Like

Check the log. It should gives you which id is failing.
In my case, I have added a regular expression match on the movie ID String and passed the integration test.

Thanks, I’ve got the code now. The reason exacly was in the validIdValue() method in

If I understand you explicitly detect the exact error by checking for ‘foobar’. This means that if a user of your API sends another invalid id, like for example ‘TryToCrackYuanCode’, your API will fail because your regex won’t catch this error. If was going to write a unit test, I won’t use a hard coded value like foobar just to make sure that I catch errors like yours.

There is 2 way to write the proper code, with a try/catch or even better with a call to isValid().

No, my regex is like “^[A-Fa-f0-9]+$” which only matches hexadecimal. I actually don’t know how many id strings the integration test would test. But I realized that “foobar” is not a hexadecimal so I went back to my validID() method and added this regex matching.

This is too permissive. An object id has to have a certain length.

@Yuan_91024 you do not need to a regular expression to check this.
In java, throwing exceptions is ok!


You are right. Best practice probably would be using isValid() method.