Custom exceptions

Hi! I’m trying to implement a new custom exception in my app, I’ve read the documentation here: Error Handling · ServiceStack/ServiceStack Wiki · GitHub, I’ve searched in the examples but I can’t find a concrete implementation of it and I’m a bit lost…
In my SetConfig I have:

SetConfig(new HostConfig {
    MapExceptionToStatusCode = {
        { typeof(MyCustomException), 404 }
    }
});

then in my service I throw the exception like this:

throw new MyCustomException("my error message");

The problem is that I don’t know how to implement MyCustomException exception… I just need to have a ResponseStatus with an error message and for the status code, if I understand right, it is already defined in the MapExceptionToStatusCode (404).
So I tried to develop it like this:

    public class MyCustomException : Exception, IResponseStatusConvertible
    {
        public string MyMessage { get; set; }

        public ResponseStatus ToResponseStatus()
        {
            return new ResponseStatus
            {
                ErrorCode = GetType().Name,
                Message = Message,
                Errors = new List<ResponseError> {
                    new ResponseError {
                        Message = MyMessage
                    }
                }
            };
        }    
    }

I don’t know if I understood how it works… but when I try to trigger the exception I get an error:

An exception of type ‘Test.ServiceInterface.MyCustomException’ occurred in Test.ServiceInterface.dll but was not handled in user code

Is there something I miss or I’ve misunderstood?

Thank you.

This should be very straight forward, you can have your exceptions implement the IResponseStatusConvertible to return a custom ResponseStatus and implement IHasStatusCode to return a custom HTTP StatusCode then you can throw your custom exception in the Service.

I’ve added an example of this in this commit which shows this working as advertised:

Create a Custom Exception:

public class Custom404Exception : Exception, 
    IResponseStatusConvertible, IHasStatusCode
{
    public Custom404Exception(string message) : base(message) {}

    public ResponseStatus ToResponseStatus()
    {
        return new ResponseStatus {
            ErrorCode = GetType().Name,
            Message = this.Message,
            Errors = new List<ResponseError> {
                new ResponseError {
                    ErrorCode = "FieldErrorCode",
                    Message = "FieldMessage",
                    FieldName = "FieldName",
                }
            }
        };
    }

    public int StatusCode { get { return (int)HttpStatusCode.NotFound; } }
}

Throw it in your Service:

[Route("/throwcustom404")]
public class ThrowCustom404 { }

public class HttpErrorService : Service
{
    public object Any(ThrowCustom404 request)
    {
        throw new Custom404Exception("Custom Status Description");
    }
}

Which returns the custom Status Code and ResponseStatus as documented:

var client = new JsonServiceClient(BaseUrl);

try
{
    var response = client.Get<string>(new ThrowCustom404());
}
catch (WebServiceException webEx)
{
    Assert.That(webEx.StatusCode, Is.EqualTo(404));
    var status = webEx.ResponseStatus;
    Assert.That(status.ErrorCode, Is.EqualTo(typeof(Custom404Exception).Name));
    Assert.That(status.Message, Is.EqualTo("Custom Status Description"));
    Assert.That(status.Errors[0].ErrorCode, Is.EqualTo("FieldErrorCode"));
    Assert.That(status.Errors[0].Message, Is.EqualTo("FieldMessage"));
    Assert.That(webEx.ResponseStatus.Errors[0].FieldName, Is.EqualTo("FieldName"));
}

Hi mythz… I appreciate your help, it clarified me how to implement the Custom404Exception but I think I’m missing something more… I always get the compiler error:

An exception of type ‘ExceptionTest.ServiceInterface.Custom404Exception’ occurred in ExceptionTest.ServiceInterface.dll but was not handled in user code

but I would it returns the serialization of the error with StatusCode 404, something like:

{
   "ResponseStatus": {
      "ErrorCode": "Custom404Exception",
      "Message": "Custom Status Description"
   }
}

I uploaded a little test repo for you to see here: https://goo.gl/TmsFct

Can you please be more specific about where/how you got the error, i.e. In browser, client, server, html or json, etc.

Please post the raw HTTP request and Response so we can see exactly what response you’re getting for what request - you can use Fiddler or network tab in Chrome WebInspector to get the HTTP request headers.

Hi mythz, the error occurs when I try to trigger the exception like that: http://localhost:49495/throwcustom404 I can’t get nothing back because my code stops here (on the server):

I know it’s a VS debugger problem that I can silence in Exceptions settings but it pops out even in Release mode… Shouldn’t I get the correct HTTP response in Release mode?

What the? You’re reporting a problem with the VS.NET debugger behavior and you didn’t think of mentioning that you’re talking about the message in the VS Exception dialog? How was anyone supposed to know you’re referring to text in an IDE dialog?

The only checkbox right in the middle of the dialog controls whether it should break on Exceptions or not.

In future please only post issues with ServiceStack libraries and include the raw HTTP Request and Response headers so we have a chance to determine what the issue is.