B
B
Bogdan2017-08-01 12:20:11
JavaScript
Bogdan, 2017-08-01 12:20:11

RAILS + AJAX + Error?

Hello. Tell me how to correctly display an error (syntactic or logical), the one that is written in the log file.
Previously, when it was implemented on JQuery.ajax, these errors were caught and they could be displayed in the browser. Now I rewrote everything to fetch () and now it only writes, error 500. And all the details are only in the log file
, here is the JS function that implements AJAX.

static ajax( caption, url, type, dataValue, dataType, callSuccess, loader = true ) {
    this.pageLoader( loader );

    const scriptRun = text => {
      const script = document.createElement( 'script' );
      script.innerHTML = text;
      document.head.appendChild( script );
    };

    const success = data => {
      if ( dataType === 'json' ) {
        if ( data.status ) {
          const { href, view } = data;

          if ( href ) {
            if ( href.search( /.pdf$/i ) === -1 ) this.assignLocation( href ); else window.open( href );
          } else if ( view ) {
            document.getElementById( 'view' ).innerHTML( view );
          }
          if ( callSuccess ) callSuccess( );
        } else {
          this.errorMsg( data.caption || caption, JSON.stringify( data.message, null, ' ' ) );
        }
      } else if ( dataType === 'script' ) {
        scriptRun( data );
      }

      if ( loader ) this.pageLoader( false );
    };

    const sendAjax = async ( ) => {
      let data = '';
      const headers = { 'Content-Type': 'application/json' };
      const body = dataValue ? JSON.stringify( dataValue ) : '';

      const credentials = 'same-origin';
      const respond = await fetch( url, { method: type, body, headers, credentials } );
      if ( respond.ok ) {
        if ( dataType === 'json' ) {
          data = await respond.json( );
        } else if ( dataType === 'script' ) {
          data = await respond.text( );
        }
      } else {
        const message =  { status: respond.status, statusText: respond.statusText };
        throw new Error( JSON.stringify( message, null, ' ' ) );
      }

      return data;
    };

    sendAjax( )
      .then( data => success( data ) )
      .catch( reason => this.errorMsg( caption, reason ) );
  }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question