Promises: Modify Rejection Value

A pattern for how to modify a rejection value, without, interrupting down-chain catch handlers. Like one might do to resolve error messages from API responses, for example.

by Matthew Marcus

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.0/bluebird.min.js"></script>
<!--

A pattern for how to modify a rejection value, without, interrupting down-chain catch handlers.  Like one might do to resolve error messages from API responses, for example.

//-->

Babel + JSX

const P = Promise.noConflict()

function getIt() {
  return new P((resolve, reject) => {
    setTimeout(() => {
    	reject({
        error: {
        	status: 400,
          body: {
            header: {
              messages: [123, 456]
            }
          }
        }
      })
    }, 100)
  })
}

function fireIt () {
  return getIt().then(
    resp => resp).catch(
    resp => {
      resp.error.body.header.messages.reverse()
      throw resp
    }
  )
}

fireIt().then((resp) => {
  console.log(`resolved => `, resp)
})
.catch((resp) => {
	console.log(`catch => `, resp)
})