The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Kelp::Exception - Tiny HTTP exceptions

SYNOPSIS

    Exception->throw(400, body => 'The request was malformed');

    # code is optional - 500 by default
    Kelp::Exception->throw;

    # can control what user sees - even in deployment (unlike string exceptions)
    Kelp::Exception->throw(501, body => {
        status => \0,
        error => 'This method is not yet implemented'
    });

DESCRIPTION

This module offers a fine-grained control of what the user sees when an exception occurs. Generally, this could also be done by setting the result code manually, but that requires passing the Kelp instance around and does not immediately end the handling code. Exceptions are a way to end route handler execution from deep within the call stack.

This implementation is very incomplete and can only handle 4XX and 5XX status codes, meaning that you can't do redirects and normal responses like this. It also tries to maintain some degree of compatibility with HTTP::Exception without its complexity.

ATTRIBUTES

code

HTTP status code. Only possible are 5XX and 4XX.

Readonly.

body

Required. Body of the request - can be a string for HTML and a hashref / arrayref for JSON responses.

A string will be passed to $response->render_error to be rendered inside an error template, if available. A reference will be JSON encoded if JSON is available, otherwise will produce an exception.

Content type for the response will be set accordingly.

METHODS

throw

    # both do exactly the same
    Kelp::Exception->throw(...);
    die Kelp::Exception->new(...);

Same as simply constructing and calling die on an object.

CAVEATS

  • Code 500 exceptions will not be logged, as it is considered something that a web developer know about. They are not thrown anywhere in Kelp internal code, so only user code can fall victim to this.

  • If there is no content type set, and the exception body is not a reference, then a text/html content type will be guessed and the body text will be passed to an error template, if available.