wrapper function that handles exceptions and logs errors this is to make sure handler_t never throws exceptions; instead, it returns an error response
| 33 | // wrapper function that handles exceptions and logs errors |
| 34 | // this is to make sure handler_t never throws exceptions; instead, it returns an error response |
| 35 | static server_http_context::handler_t ex_wrapper(server_http_context::handler_t func) { |
| 36 | return [func = std::move(func)](const server_http_req & req) -> server_http_res_ptr { |
| 37 | std::string message; |
| 38 | error_type error; |
| 39 | try { |
| 40 | return func(req); |
| 41 | } catch (const std::invalid_argument & e) { |
| 42 | // treat invalid_argument as invalid request (400) |
| 43 | error = ERROR_TYPE_INVALID_REQUEST; |
| 44 | message = e.what(); |
| 45 | } catch (const std::exception & e) { |
| 46 | // treat other exceptions as server error (500) |
| 47 | error = ERROR_TYPE_SERVER; |
| 48 | message = e.what(); |
| 49 | } catch (...) { |
| 50 | error = ERROR_TYPE_SERVER; |
| 51 | message = "unknown error"; |
| 52 | } |
| 53 | |
| 54 | auto res = std::make_unique<server_http_res>(); |
| 55 | res->status = 500; |
| 56 | try { |
| 57 | json error_data = format_error_response(message, error); |
| 58 | res->status = json_value(error_data, "code", 500); |
| 59 | res->data = safe_json_to_str({{ "error", error_data }}); |
| 60 | SRV_WRN("got exception: %s\n", res->data.c_str()); |
| 61 | } catch (const std::exception & e) { |
| 62 | SRV_ERR("got another exception: %s | while handling exception: %s\n", e.what(), message.c_str()); |
| 63 | res->data = "Internal Server Error"; |
| 64 | } |
| 65 | return res; |
| 66 | }; |
| 67 | } |
| 68 | |
| 69 | int main(int argc, char ** argv) { |
| 70 | // own arguments required by this example |
no test coverage detected