|
| 1 | +{*! |
| 2 | + * Fano Web Framework (https://fanoframework.github.io) |
| 3 | + * |
| 4 | + * @link https://github.com/fanoframework/fano |
| 5 | + * @copyright Copyright (c) 2018 - 2021 Zamrony P. Juhara |
| 6 | + * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) |
| 7 | + *} |
| 8 | + |
| 9 | +unit WithExceptMiddlewareExecutorImpl; |
| 10 | + |
| 11 | +interface |
| 12 | + |
| 13 | +{$MODE OBJFPC} |
| 14 | + |
| 15 | +uses |
| 16 | + |
| 17 | + RequestIntf, |
| 18 | + ResponseIntf, |
| 19 | + RouteHandlerIntf, |
| 20 | + MiddlewareExecutorIntf, |
| 21 | + DecoratorMiddlewareExecutorImpl; |
| 22 | + |
| 23 | +type |
| 24 | + |
| 25 | + (*!------------------------------------------------ |
| 26 | + * decorator class having capability to |
| 27 | + * execute middlewares stack and rethrow any exception |
| 28 | + * as EHttpException. |
| 29 | + * This class is implemented to fix issue response headers |
| 30 | + * set previously gone when exception is raised |
| 31 | + * https://github.com/fanoframework/fano/issues/17 |
| 32 | + * |
| 33 | + * @author Zamrony P. Juhara <[email protected]> |
| 34 | + *-----------------------------------------------*) |
| 35 | + TWithExceptMiddlewareExecutor = class (TDecoratorMiddlewareExecutor) |
| 36 | + public |
| 37 | + function execute( |
| 38 | + const request : IRequest; |
| 39 | + const response : IResponse; |
| 40 | + const routeHandler : IRouteHandler |
| 41 | + ) : IResponse; override; |
| 42 | + end; |
| 43 | + |
| 44 | +implementation |
| 45 | + |
| 46 | +uses |
| 47 | + |
| 48 | + sysutils, |
| 49 | + EHttpExceptionImpl, |
| 50 | + EInternalServerErrorImpl; |
| 51 | + |
| 52 | + function TWithExceptMiddlewareExecutor.execute( |
| 53 | + const request : IRequest; |
| 54 | + const response : IResponse; |
| 55 | + const routeHandler : IRouteHandler |
| 56 | + ) : IResponse; |
| 57 | + begin |
| 58 | + try |
| 59 | + result := inherited execute(request, response, routeHandler); |
| 60 | + except |
| 61 | + on e: EHttpException do |
| 62 | + begin |
| 63 | + //re raise but make sure add response header so that |
| 64 | + //it is not gone (see Issue #17) |
| 65 | + e.headers := e.headers + response.headers.asString(); |
| 66 | + raise e; |
| 67 | + end; |
| 68 | + |
| 69 | + on e: Exception do |
| 70 | + begin |
| 71 | + //re raise but add response header so that |
| 72 | + //it is not gone (see Issue #17) |
| 73 | + raise EInternalServerError.create( |
| 74 | + //add original class name in exception message |
| 75 | + //so that we know type of original exception is |
| 76 | + '(' + e.ClassName . ') ' + e.Message, |
| 77 | + response.headers.asString() |
| 78 | + ); |
| 79 | + end; |
| 80 | + end; |
| 81 | + end; |
| 82 | + |
| 83 | +end. |
0 commit comments