JNevens
JNevens

Reputation: 12012

Smalltalk Error handling with Transcript

Suppose I have the following method:

MyClass>>addCategory: aCategory toEvent: anEvent
    | cat |
    cat := anEvent addCategory: aCategory
    ...

Now, the method #addCategory can either return some other object (e.g. something of class Foo) or throw an error (using Error signal: 'message').

I have been looking at aBlock ifError: aBlock, something like this:

MyClass>>addCategory: aCategory toEvent: anEvent
    | cat |
    cat := [anEvent addCategory: aCategory] ifError: [ :err | Transcript show: err. ]
    ...

But I can't quite figure out how to handle the variable cat afterwards, in order to get the behavior I want.

Upvotes: 1

Views: 191

Answers (2)

Leandro Caniglia
Leandro Caniglia

Reputation: 14843

Here is another way to do the same. The idea is to enclose your code as if would not fail and wrap it with an on: Error

MyClass>>addCategory: aCategory toEvent: anEvent
  | cat |
  [
    cat := anEvent addCategory: aCategory.
    Transcript show: 'Category added!']
    on: Error
    do: [:err | Transcript show: err messageText].
 ^cat

Notice that cat will not get assigned in case of Error and hence the method will answer with nil. Notice also that there is no need to ^nil from within the error-handler block.

Remember that the idea of on:do: is to allow you to write naïve code and then handle possible error conditions without inlining them into the error-free section of your code.

[
 <my naive
 and clean
 lines of code>] on: Error do: [:err | oops!]

Your solution is ok but inlines error handling code inside the main code, making it a little bit harder for the reader to get the main idea of the relevant code.

Upvotes: 3

JNevens
JNevens

Reputation: 12012

One possible way to solve this is the following:

MyClass>>addCategory: aCategory toEvent: anEvent
    | cat |
    cat := [ anEvent addCategory: aCategory] on: Error do [ :err | Transcript show: err messageText. ^nil. ]
    Transcript show: 'Category added!'.
    ^cat

This solution will print the error to the Transcript and return nil from the method. In case there is no error, the code will continue, print the message on the Transcript and return the object.

This might not be the best solution, but it is one possible way of doing it. As long as you don't mind that nil is returned in case of an error.

Upvotes: 0

Related Questions