3

In domain model of my web application I've an entity Foo which can be created only by a pojo FooBean: Foo.newInstance(FooBean fooBean) (Might have been better a Builder-pattern.)

In the factory methode newInstance() the pojo FooBean is validated and throws NullPointerExceptions and IllegalArgumentExceptions if needed. The fields of the pojo are filled by a form on the presentation layer. That form does some validation on the user input and shows user friendly messages if needed.

The exception message of the NullPointerExceptions and IllegalArgumentExceptions thrown in the newInstance() method are rather technical and shouldn't be displayed to the end user.

What is a proper way to show user friendly error messages that are originated by the NullPointerException or the IllegalArgumentException?

gnat
  • 21,442
  • 29
  • 112
  • 288
Bart Weber
  • 297
  • 1
  • 2
  • 8
  • 2
    Catch the exceptions higher up the call stack and present a user-friendly message? – Doval May 14 '14 at 13:52
  • possible duplicate of [Logging errors caused by exceptions deep in the application](http://programmers.stackexchange.com/questions/151967/logging-errors-caused-by-exceptions-deep-in-the-application) – gnat May 14 '14 at 14:03
  • See also: [Recommend a design pattern/approach to exposing/tolerating/recovering from system errors, Exception handling...](http://programmers.stackexchange.com/questions/109297/recommend-a-design-pattern-approach-to-exposing-tolerating-recovering-from-syste) – gnat May 14 '14 at 14:07
  • The NullPointerException and IllegalArgumentException are probably too much generic. When I catch these exceptions I don't know enough to differentiate between a programming error or bad user input. Probably (like Andy says [here](http://programmers.stackexchange.com/a/201310/125534)) I should use a specialized exception (and since I'm using Java I should use a checked exception for that). – Bart Weber May 14 '14 at 15:01

1 Answers1

2

Be specific, throw early, and catch late.

I think you are missing both the "be specific" as well as the "catch" parts.

You should be throwing descriptive exceptions and handling them as appropriate, where appropriate.

BrandonV
  • 1,356
  • 1
  • 10
  • 15
  • 1
    Very useful article. Thank you. What would be nice to add to this article is the concept of [Exception Translation](http://www.javapractices.com/topic/TopicAction.do?Id=120). – Bart Weber May 15 '14 at 10:59