Handle Exceptions like a Professional (Part 2)

Plain Exceptions

Newing up and throwing a plain base Exception. Avoid.
  • Must Catch All Exceptions. Since we are throwing an instance of the most basic exception type, the only way for us to catch and handle the exception is to catch all exceptions. It’s akin to putting a net out to catch all fish even though we may only be interested in Yellow Fin Tuna above a specific size.
  • Identify Exception by Message. The only way for us to identify and distinguish this exception from others is via the Message property set during construction. Another developer could easily change the Message string of the thrown exception. The catch part of the code would be fragile — this is a coding antipattern.
  • It’s the client’s fault — The client has sent through bad data. Error codes: 4xx (eg. 400 — Bad Request)
  • It’s the server’s fault — The server has failed to respond to a valid request. Error codes: 5xx (eg. 500 — Internal Server Error)
  • 400 — Bad Request. The server should respond with this HTTP status code when the client is sending through invalid data, and a business rule in our server-side code is triggered.
  • 401 — Unauthorised. The authentication details in the request are either lacking, incomplete or wrong. This status code has the wrong name — it should be 401 — Unauthenticated.
  • 403 — Forbidden. The system is letting the client know that they are not authorised to perform this action.
  • 404 — Not Found. The server could not find the given resource. It may not ever have existed, or someone may have deleted it already.

Authentication vs Authorisation — Quick Interlude

  • Authentication must always come before Authorisation.
  • Authorisation is always binary, either true or false.
  • Authorisation applies to an action or resource.
  • ClientInputException ⇒ 400 — Bad Request
  • UnauthenticatedException ⇒ 401 — Unauthorised
  • UnauthorizedException ⇒ 403 — Forbidden
  • NotFoundException ⇒ 404 — Not Found
  • InvalidAccountGroupName
  • InvalidBankAccountNumber
  • InvalidDate

Catching of ClientInputExceptions


Join Hundreds of Software Engineers and get my Code Coach Programming Tips delivered to your inbox every weekday.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store