Created
February 17, 2012 16:41
-
-
Save mikeobrien/1854291 to your computer and use it in GitHub Desktop.
RESTful exception handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Conventions : FubuRegistry | |
{ | |
public Conventions() | |
{ | |
// ... | |
Policies.ConditionallyWrapBehaviorChainsWith<HandledExceptionBehavior>(x => x.BehaviorChain.Last() is JsonSerializer); | |
// ... | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EntityValidationException : Exception, IValidationException { | |
public EntityValidationException(string propertyName, string validationError) { | |
Name = propertyName; | |
Details = validationError; | |
} | |
public string Name { get; private set; } | |
public string Details { get; private set; } | |
// ... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HandledExceptionBehavior : IActionBehavior | |
{ | |
private readonly IActionBehavior _innerBehavior; | |
private readonly IOutputWriter _outputWriter; | |
public ExceptionHandlerBehavior( | |
IActionBehavior innerBehavior, | |
IOutputWriter outputWriter) | |
{ | |
_innerBehavior = innerBehavior; | |
_outputWriter = outputWriter; | |
} | |
public void Invoke() | |
{ | |
try | |
{ | |
_innerBehavior.Invoke(); | |
} | |
catch (Exception e) | |
{ | |
if (e is IValidationException) SetStatus("304.1", ((IValidationException)e).Details); | |
else if (e is IAuthorizationException) SetStatus("302", "You are not authorized to do this."); | |
// ... | |
else throw; | |
} | |
} | |
private void SetStatus(string code, string message) | |
{ | |
_outputWriter.WriteResponseCode(code); | |
_outputWriter.WriteResponseMessage(message); | |
} | |
public void InvokePartial() | |
{ | |
_innerBehavior.InvokePartial(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IValidationException { | |
public string Name { get; } | |
public string Details { get; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment