Skip to content

Handling HTTP Errors

Eugene edited this page Jun 21, 2021 · 2 revisions

Server: Sending an Error

  1. Set the response header as usual
  2. Set the message to send back to the client
  3. Set the HTTP response code
  4. Return the server's response code
static onion_connection_status handler_root(void *_, onion_request *req, onion_response *res) {
  build_response_header(res);
  onion_response_printf(res, "SWTbahn server");
  onion_response_set_code(res, HTTP_BAD_REQUEST);

  return OCS_PROCESSED;
}

Client: Displaying an Error

jQuery ajax is used to communicate with the server asynchronously. For the error handler, the response text is contained in the first parameter of ajax, which is a jqXHR Object.

$('#pingButton').click(function () {
  $('#pingResponse').text('Waiting');
  $.ajax({
    type: 'POST',
    url: '/',
    crossDomain: true,
    data: null,
    dataType: 'text',
    success: function (responseData, textStatus, jqXHR) {
      $('#pingResponse').parent().removeClass('alert-danger');
      $('#pingResponse').parent().addClass('alert-success');
      $('#pingResponse').text('OK');
    },
    error: function (responseData, textStatus, errorThrown) {
      $('#pingResponse').parent().removeClass('alert-success');
      $('#pingResponse').parent().addClass('alert-danger');
      $('#pingResponse').text(responseData.responseText);
    }
  });
});