-
-
Save osben/f9f8befca4ba41890931b4825f56cdb6 to your computer and use it in GitHub Desktop.
RxJS operator for throwing semantic errors for certain HTTP status codes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable, throwError } from 'rxjs' | |
import { catchError } from 'rxjs/operators' | |
import { HttpErrorResponse } from '@angular/common/http' | |
export const throwForCodes = (codeErrors: Array<[number, () => Error]>) => { | |
const mappedCodeErrors = new Map(codeErrors) | |
return <T>(source: Observable<T>) => | |
source.pipe(catchError(error => { | |
if (error instanceof HttpErrorResponse) { | |
const mappedErrorFn = mappedCodeErrors.get(error.status) | |
return throwError(mappedErrorFn ? mappedErrorFn() : error) | |
} | |
return throwError(error) | |
})) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { throwForCodes } from './throw-for-codes'; | |
import { HttpErrorResponse } from '@angular/common/http' | |
import { NOT_FOUND, CONFLICT } from 'http-status-codes' | |
import { throwError } from 'rxjs' | |
describe('throwForCodes', () => { | |
it('should rethrow mapped error', done => { | |
const httpError = new HttpErrorResponse({status: NOT_FOUND}) | |
const message = 'User not found' | |
throwError(httpError).pipe(throwForCodes([ | |
[NOT_FOUND, () => new Error(message)] | |
])) | |
.subscribe( | |
() => fail(), | |
err => { | |
expect(err.message).toEqual(message) | |
done() | |
} | |
) | |
}); | |
it('should rethrow original error for unmapped errors', done => { | |
const httpError = new HttpErrorResponse({status: CONFLICT}) | |
const message = 'User not found' | |
throwError(httpError).pipe(throwForCodes([ | |
[NOT_FOUND, () => new Error(message)] | |
])) | |
.subscribe( | |
() => fail(), | |
err => { | |
expect(err).toEqual(httpError) | |
done() | |
} | |
) | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment