NestJS handle HttpModule errors - rxjs

NestJS has the following example for using their HttpModule:
#Injectable()
export class CatsService {
constructor(private readonly httpService: HttpService) {}
findAll(): Observable<AxiosResponse<Cat[]>> {
return this.httpService.get('http://localhost:3000/cats');
}
}
My question is, how does the client code (most likely a Controller) handle this response? How does it treat Observables so that Cat[] may be accessed. Or what if the Http request throws an error such as a 404.
How does a NestJS client (Controller) in this case interact with the findAll() method provided by the service?

I am not too familiar with NestJs, but if you want to run an observable http request generally you do the following to consume and catchError
this.catService.findAll().pipe(
// axio wraps the result in data
map(res=>res.data),
catchError(e=>{
...handle error 404
return of(e)
})).subscribe()

If, for whatever reason, the URL you provide to the HttpService returns a 404, that error will propagate back through the service, to the controller, and eventually to the client that called the original URL. Under the hood, NestJS will subscribe to all returned Observables so that you don't need to worry about it, you can just return the call directly from your Controller. So in the example above, say we have a controller that looks like this:
#Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {}
#Get()
findAllCats(): Observable<Cat[]> {
return this.catsService.findAll();
}
}
And CatsService looks like this
#Injectable()
export class CatsService {
constructor(private readonly httpService: HttpService) {}
findAll(): Observable<Cat[]> {
return this.httpService.get('http://localhost:3000/cats');
}
}
Assuming you are calling off to another server (i.e. this server is not running on port 3000) and /cats is not a valid endpoint and that server returns a 404 to you, the httpService's response will bubble up through the CatsService to the CatsController where NestJS will handle the subscription, and send the response back to the client. If you are looking to do some custom error handling, that will need to be handled in a different way. A great way to test how the HttpService responds to things is to create a simple endpoint and call off to a bad URL (like https://google.com/item which is a 404)

Related

NestJS Microservice Exception handling

I have setup a Microservice Architecture that looks the following:
api-gateway (NestFactory.create(AppModule);)
service 1 (NestFactory.createMicroservice<MicroserviceOptions>)
service 2 (NestFactory.createMicroservice<MicroserviceOptions>)
...
A Service looks like this:
service.controller.ts
service.handler.ts
Where handler is like a Service in a typical Monolith that handles the logic.
Currently, I am catching Exceptions the following way:
The handler makes a call to the database and fails due to a duplicated key (i.e. email).
I catch this exception and convert it to an RpcException
In the ApiGateway I catch the RpcException like so:
return new Promise<Type>((resolve, reject) => {
this.clientProxy
.send<Type>('MessagePattern', { dto: DTO })
.subscribe(resolve, (err) => {
logger.error(err);
reject(err);
});
});
Again I have to catch the rejected Promise and throw an HttpException to have the ExceptionFilter sending a proper error response. Throwing an Error inside the Promise instead of rejecting it doesn't work)
So basically, I have 3 TryCatch Blocks for 1 Exception.
This looks very verbose to me.
Is there any better way or best practice when it comes to NestJS Microservices?
Can we have an Interceptor for the rebound messages received by this.clientProxy.send and pipe it to send send the error response to the client without catching it 2 times explicitly?
Not a complete answer to your question, but it's better than nothing. :)
I try to avoid the .subscribe, reject(...) approach whenever possible.
Even though the send method returns an Observable, in most cases you expect only 1 response. So, in most cases .toPromise() makes sense.
Once it's a promise, you can use the async-await syntax, and you don't have callbacks and you can effectively just catch all exceptions (and rethrow if you want to). It helps a bit.
try {
const payload = { dto: DTO };
const response = await this.clientProxy.send<Type>('MessagePattern', payload).toPromise();
} catch (err) {
this.logger.error(err);
}
On the server side, you can effectively define Interceptors, which are almost identical to the Interceptors you would use for API controllers.
#MessagePattern(messagePattern)
#UseInterceptors(CatchExceptionInterceptor)
public async someMethod(...) { }
You should implement the NestInterceptor interface:
#Injectable()
export class CatchExceptionInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
return stream$.pipe(
catchError(...)
);
}
}

Handle data after http get request in angular

I have a service that requests data from a get method, I'd like to map the response to an object storing some Ids and use those Ids to make other http requests.
I was told this isn't usually done in a callback manner, I looked at this How do I return the response from an asynchronous call? but I don't think it's the usual way to implement services, any hints are very appreciated.
Tried adding in onInit/constructor method in angular to be sure the object was filled before other methods were called without success.
#Injectable ()
export class ContactService {
storeIds;
getIds(callback: Function) {
this.http.get<any>(IdsUrl, Config.options).subscribe(res => {
callback(response);
});
getIds(res => {
this.storeIds = {
profileId: res.profile,
refIds: res.refIds
}
}
)
// this.storeIds returns undefined as it's an async call
this.http.post<any>(WebserviceUrl + this.storeIds.profileId , data, headers )
// .....Many other web services that relay on this Ids
}
Just create another service called StoreIdsService. Update the response you get from your first api call 'getIds' in the StoreIdsService. The idea is to have StoreIdsService as singleton service to keep state of your storeIds. You can inject StoreIdsService in anywhere component you want to get the storeIds.
Its one of manyways to share data in angular between components.
Please refer to this answer someone has posted.
How do I share data between components in Angular 2?
You can simply assign the service response to the storeIds property inside the subscribe method. and call the subsequent services inside it if you need.
#Injectable ()
export class ContactService {
storeIds;
getIds() {
this.http.get<any>(IdsUrl, Config.options).subscribe(res => {
this.storeIds = {
profileId: response.profile,
refIds: response.refIds
}
this.otherapicall1();
this.otherapicall2();
});
}

Can I access the request/response body on an ExchangeFilterFunction?

Given an exchange using WebClient, filtered by a custom ExchangeFilterFunction:
#Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request)
.doOnSuccess(response -> {
// ...
});
}
Trying to access the response body more than once using response.bodyToMono() will cause the underlying HTTP client connector to complain that only one receiver is allowed. AFAIK, there's no way to access the body's Publisher in order to cache() its signals (and I'm not sure it'd be a good idea, resource-wise), as well as no way to mutate or decorate the response object in a manner that allows access to its body (like it's possible with ServerWebExchange on the server side).
That makes sense, but I am wondering if there are any ways I could subscribe to the response body's publisher from a form of filter such as this one. My goal is to log the request/response being sent/received by a given WebClient instance.
I am new to reactive programming, so if there are any obvious no-nos here, please do explain :)
Only for logging you could add a wiretap to the HttpClient as desribed in this answer.
However, your question is also interesting in a more general sense outside of logging.
One possible way is to create a duplicate of the ClientResponse instance with a copy of the previous request body. This might go against reactive principles, but it got the job done for me and I don't see big downsides given the small size of the response bodies in my client.
In my case, I needed to do so because the server sending the request (outside of my control) uses the HTTP status 200 Ok even if requests fail. Therefore, I need to peek into the response body in order to find out if anything went wrong and what the cause was. In my case I evict a session cookie in the request headers from the cache if the error message indicates that the session expired.
These are the steps:
Get the response body as a Mono of a String (cf (1)).
Return a Mono.Error in case an error is detected (cf (2)).
Use the String of the response body to build a copy of the original response (cf (3)).
You could also use a dependency on the ObjectMapper to parse the String into an object for analysis.
Note that I wrote this in Kotlin but it should be easy enough to adapt to Java.
#Component
class PeekIntoResponseBodyExchangeFilterFunction : ExchangeFilterFunction {
override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> {
return next.exchange(request)
.flatMap { response ->
// (1)
response.bodyToMono<String>()
.flatMap { responseBody ->
if (responseBody.contains("Error message")) {
// (2)
Mono.error(RuntimeException("Response contains an error"))
} else {
// (3)
val clonedResponse = response.mutate().body(responseBody).build()
Mono.just(clonedResponse)
}
}
}
}
}

Can an Owin Middleware return a response earlier than the Invoke method returns?

I have the following middleware code:
public class UoWMiddleware : OwinMiddleware
{
readonly IUoW uow;
public UoWMiddleware(OwinMiddleware next, IUoW uow) : base(next)
{
this.uow = uow;
}
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch
{
uow.RollBack();
throw;
}
finally
{
if (uow.Status == Base.SharedDomain.UoWStatus.Running)
{
var response = context.Response;
if (response.StatusCode < 400)
{
Thread.Sleep(1000);
uow.Commit();
}
else
uow.RollBack();
}
}
}
}
Occasionally we observe that the response returns to client before calling uow.Commit() via fiddler. For example we put a break point to uow.Commit and we see the response is returned to client despite that we are on the breakpoint waiting. This is somewhat unexpected. I would think the response will strictly return after the Invoke method ends. Am I missing something?
In Owin/Katana the response body (and, of course, the headers) are sent to the client at the precise moment when a middleware calls Write on the Response object of the IOwinContext.
This means that if your next middleware is writing the response body your client will receive it before your server-side code returns from the call to await Next.Invoke().
That's how Owin is designed, and depends on the fact that the Response stream may be written just once in a single Request/Response life-cycle.
Looking at your code, I can't see any major problem in such behavior, because you are simply reading the response headers after the response is written to the stream, and thus not altering it.
If, instead, you require to alter the response written by your next middleware, or you strictly need to write the response after you execute further logic server-side, then your only option is to buffer the response body into a memory stream, and than copy it into the real response stream (as per this answer) when you are ready.
I have successfully tested this approach in a different use case (but sharing the same concept) that you may find looking at this answer: https://stackoverflow.com/a/36755639/3670737
Reference:
Changing the response object from OWIN Middleware

Returning error from SignalR server method

I am new to SignalR and there is a small detail I can't get my head around.
My SignalR hub include many channels and the clients can join one or many of these channels via a server method:
joinChannel(string channelName)
What I don't understand is what this method should return.
If it were a normal "RPC" method I would return a status (200 - Ok, 404 - Not found, 403 - Forbidden etc) via IHttpActionResult.
How do I indicate success/failure in SignalR?
What determines if the reply gets to .done or .fail in the client?
Update
Currently my method returns a non-zero value in case of error.
int joinChannel(string channelName) {
...
return errorCode;
}
This works but it create unnecessarily complicated code in the client
hubProxy.server.joinChannel('channel1')
.done(function (result) {
if (result != 0) {
// error handling
}
})
.fail(function (error) {
// error handling
});
To confirm that your action was successfully performed, you can have a client method call. So, basically it would look like this:
public void ServerMethod(argumentList)
{
if (/* server code executed successfully */)
Clients.Caller.onSuccess(arguments);
else Clients.Caller.onFailure(arguments);
}
What this piece of code does is to notify the caller of the server method of a success/failure by calling a client method - method defined in JavaScript. You can also have a method executed on All clients, or only on specific users.
Since it is not an RPC mechanism, I think this is the closest thing you can do to simulate a return type in SignalR.
Hope this helps!
Best of luck!
What about
HubException in
Microsoft.AspNetCore.SignalR.
This is available in ASP.NET Core.
This exception is thrown on the server and sent to client. You can also derive from that class to put your own information in it.

Resources