This seems like a pretty efficient way to do error handling, but I want to know how to do it correctly if this is smelly:
Class Widget
...
Public Function IsValid() As Boolean
If (some condition isnt met) Then
Throw New ApplicationException("Error message")
ElseIf (some other condition isnt met) Then
Throw New ApplicationException("Another error message")
End If
Return True
End Function
...
End Class
... (somewhere else)...
Public Function DoAwesomeStuff(id As Integer) As String
Dim w As Widget() = Widget.GetWidget(id)
If w.IsValid Then
Do Awesome Things
End If
Return a string of some sort
End Sub
... (somewhere elser)...
<WebMethod(EnableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function Add(ByVal id As Integer) As String
Try
//.ToJson is an Extension Method that serializes an obj to JSON
Return New With {.Message = DoAwesomeStuff(id)}.ToJson
Catch ex As Exception
Return New With {.Message = "Error: " & ex.Message, .Error = True}.ToJson
End Try
End Function
And then in the javascript I check for an Error property in the response and handle accordingly. It seems like it works ok for me, but I am not sure if this is smelly. I know you’re not supposed to use Try/Catch blocks for control flow, I’m just not sure if this qualifies as control flow or not.
Yes, it has a vexing exception smell.
Users of the
IsValidfunction would expect it to returnTrueorFalse.Exceptions should be used in unexpected cases, for example, if some variable needed to evaluate the validity in your
IsValidfunction is not properly initialized.If you want to have a validation failure message along with the validation status, consider using a
ByRefparameter for example, something like: