Search code examples
nginxluaopenresty

Handle lua error in nginx with rendering 500 page


I found myself trying to figure out how to handle lua errors by rendering a 500 page in nginx (instead of that white screen in openresty saying there was an internal error) without any success at the moment. Does anybody have any input how I can redirect to an error route (or another way) to show a custom 500 page?

This is my nginx config:

worker_processes  1;
error_log logs/error.log;

events {
  worker_connections 1024;
 }

http{
    server {
        server_name localhost;

        root /usr/local/openresty/nginx/html

        # Any route that starts with gallery/posts
        location ~ ^/gallery/(.+) {
          set $encoded_post_info $1;

          set_by_lua_block $decoded_post_info {
            # if this code breaks how can I get it handled?
            local base64 = require 'base64';
            local decodedPostInfo = base64.decode(ngx.var.encoded_post_info);

            return decodedPostInfo;
          }

          rewrite ^ /index.html break;
        }

        # Any route that doesn't have a file extension (e.g. /devices)
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

Solution

  • You can try error_page for a custom error page

    location /lua_error {
      content_by_lua_block {
        # Some error by lua
      }
      error_page 500 /500.html
    }
    
    

    In case you want to catch the error, you might need to take a look at Alexander's comment, using pcall/xpcall. Doc here