1+ namespace SqlStreamStore . HAL
2+ {
3+ using System ;
4+ using System . Collections . Generic ;
5+ using Halcyon . HAL ;
6+ using Microsoft . Owin ;
7+ using Newtonsoft . Json ;
8+ using SqlStreamStore . Streams ;
9+ using MidFunc = System . Func < System . Func < System . Collections . Generic . IDictionary < string , object > ,
10+ System . Threading . Tasks . Task
11+ > , System . Func < System . Collections . Generic . IDictionary < string , object > ,
12+ System . Threading . Tasks . Task >
13+ > ;
14+
15+ internal static class ExceptionHandlingMiddleware
16+ {
17+ private static readonly Func < Exception , Response > s_defaultExceptionHandler
18+ = ex => new Response ( new HALResponse ( new
19+ {
20+ type = ex . GetType ( ) . Name ,
21+ title = "Internal Server Error" ,
22+ detail = ex . Message
23+ } ) ,
24+ 500 ) ;
25+
26+ private static readonly IDictionary < Type , Func < Exception , Response > > s_exceptionHandlers
27+ = new Dictionary < Type , Func < Exception , Response > >
28+ {
29+ [ typeof ( WrongExpectedVersionException ) ] = ex => new Response ( new HALResponse ( new
30+ {
31+ type = ex . GetType ( ) . Name ,
32+ title = "Wrong expected version." ,
33+ detail = ex . Message
34+ } ) , 409 ) ,
35+ [ typeof ( JsonException ) ] = ex => new Response ( new HALResponse ( new
36+ {
37+ type = ex . GetType ( ) . Name ,
38+ title = "Bad format."
39+ } ) , 400 ) ,
40+ [ typeof ( InvalidAppendRequestException ) ] = ex => new Response ( new HALResponse ( new
41+ {
42+ type = ex . GetType ( ) . Name ,
43+ title = "Bad format."
44+ } ) , 400 ) ,
45+ [ typeof ( Exception ) ] = s_defaultExceptionHandler
46+ } ;
47+
48+ public static MidFunc HandleExceptions => next => async env =>
49+ {
50+ try
51+ {
52+ await next ( env ) ;
53+ }
54+ catch ( Exception ex )
55+ {
56+ var context = new OwinContext ( env ) ;
57+
58+ var exceptionType = ex . GetType ( ) ;
59+
60+ Func < Exception , Response > exceptionHandler = null ;
61+
62+ while ( exceptionType != null )
63+ {
64+ if ( s_exceptionHandlers . TryGetValue ( exceptionType , out exceptionHandler ) )
65+ {
66+ break ;
67+ }
68+
69+ exceptionType = exceptionType . BaseType ;
70+ }
71+
72+ var response = ( exceptionHandler ?? s_defaultExceptionHandler ) ( ex ) ;
73+
74+ await context . WriteHalResponse ( response ) ;
75+ }
76+ } ;
77+ }
78+ }
0 commit comments