NestJS set HttpStatus in interceptorSetting “checked” for a checkbox with jQuery?Set a default parameter value for a JavaScript functionHow do I set/unset a cookie with jQuery?How to store Node.js deployment settings/configuration files?Error: Can't set headers after they are sent to the clientget and set in TypeScriptImplement an error interceptor based on what is shownInterceptor response modification with swagger documentationHow to ignore an interceptor for a particular route in NestJSWhy does nestjs interceptor return undefined?

Would a horse be sufficient buffer to prevent injury when falling from a great height?

Can an untrusted VPN client monitor my network activity?

How to say "respectively" in German when listing (enumerating) things

Looseness for Bezier controls. Or how to bend in circularly symmetric tikz-drawings (without bend left, etc.)

The answer is a girl's name (my future granddaughter) - can anyone help?

Calculate the Ultraradical

Approximate the perfect fifth

Confusion regarding control system of Mars Rover?

What is the meaning of first flight and introduction in aircraft production?

Windows 10 deletes lots of tiny files super slowly. Can anything that be done to speed it up?

Why the first octet of a MAC address always end with a binary 0?

Does the 'java' command compile Java programs?

What are one's options when facing religious discrimination at the airport?

Knights and Knaves: What does C say?

Impossible violin chord, how to fix this?

Lighthouse Alternatives

Duck, duck, gone!

Enlightenment finding me

IEEE 754 square root with Newton-Raphson

Should I be an author on another PhD student's paper if I went to their meetings and gave advice?

Convert a string of digits from words to an integer

How to find places to store/land a private airplane?

Can I pay some of the cost of an activated ability lots of times to get more out of the effect?

Avoiding dust scattering when you drill



NestJS set HttpStatus in interceptor


Setting “checked” for a checkbox with jQuery?Set a default parameter value for a JavaScript functionHow do I set/unset a cookie with jQuery?How to store Node.js deployment settings/configuration files?Error: Can't set headers after they are sent to the clientget and set in TypeScriptImplement an error interceptor based on what is shownInterceptor response modification with swagger documentationHow to ignore an interceptor for a particular route in NestJSWhy does nestjs interceptor return undefined?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









1















I'm using an interceptor to transform my response. I want to set the HttpStatus inside but the code I'm using now doesn't work.



import CallHandler, ExecutionContext, NestInterceptor, SetMetadata from '@nestjs/common';
import Observable from 'rxjs';
import map from 'rxjs/operators';
import classToPlain from 'class-transformer';
import ApiResponse from '../models/apiResponse';

export class TransformInterceptor implements NestInterceptor any>,
): Observable<ApiResponse










share|improve this question


























  • Please see my update. This is now possible.

    – Kim Kern
    Aug 4 at 15:58

















1















I'm using an interceptor to transform my response. I want to set the HttpStatus inside but the code I'm using now doesn't work.



import CallHandler, ExecutionContext, NestInterceptor, SetMetadata from '@nestjs/common';
import Observable from 'rxjs';
import map from 'rxjs/operators';
import classToPlain from 'class-transformer';
import ApiResponse from '../models/apiResponse';

export class TransformInterceptor implements NestInterceptor any>,
): Observable<ApiResponse










share|improve this question


























  • Please see my update. This is now possible.

    – Kim Kern
    Aug 4 at 15:58













1












1








1








I'm using an interceptor to transform my response. I want to set the HttpStatus inside but the code I'm using now doesn't work.



import CallHandler, ExecutionContext, NestInterceptor, SetMetadata from '@nestjs/common';
import Observable from 'rxjs';
import map from 'rxjs/operators';
import classToPlain from 'class-transformer';
import ApiResponse from '../models/apiResponse';

export class TransformInterceptor implements NestInterceptor any>,
): Observable<ApiResponse










share|improve this question
















I'm using an interceptor to transform my response. I want to set the HttpStatus inside but the code I'm using now doesn't work.



import CallHandler, ExecutionContext, NestInterceptor, SetMetadata from '@nestjs/common';
import Observable from 'rxjs';
import map from 'rxjs/operators';
import classToPlain from 'class-transformer';
import ApiResponse from '../models/apiResponse';

export class TransformInterceptor implements NestInterceptor any>,
): Observable<ApiResponse







javascript node.js typescript nestjs fastify






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 29 at 0:35









Kim Kern

15.9k6 gold badges43 silver badges70 bronze badges




15.9k6 gold badges43 silver badges70 bronze badges










asked Mar 28 at 20:16









toonvanstrijptoonvanstrijp

899 bronze badges




899 bronze badges















  • Please see my update. This is now possible.

    – Kim Kern
    Aug 4 at 15:58

















  • Please see my update. This is now possible.

    – Kim Kern
    Aug 4 at 15:58
















Please see my update. This is now possible.

– Kim Kern
Aug 4 at 15:58





Please see my update. This is now possible.

– Kim Kern
Aug 4 at 15:58












1 Answer
1






active

oldest

votes


















1
















Updated Answer



Since nest version 6.1.0, it is possible to set the status code in an interceptor; it will not be overwritten anymore (see this PR):



context.switchToHttp()
.getResponse()
.status(205);



Outdated Answer



Setting the status code from an Interceptor is impossible (see this issue) because:




  • sometimes response status codes are dependent on exceptions and exception filters are executed after interceptors,

  • global response controller's logic is the last step performed just before sending a final result through the network (that's the place
    where default status codes come in).



So your status code will be overridden by the default code 200/201 or an exception filter.




As a (hacky) workaround, you can use exception filters to set the status code in interceptors:



1) Create your own exception as a wrapper around HttpException:



export class StatusException extends HttpException 
constructor(data, status: HttpStatus)
super(data, status);




2) Create an exception filter that sets the response code and returns the data:



@Catch(StatusException)
export class StatusFilter implements ExceptionFilter
catch(exception: StatusException, host: ArgumentsHost)
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
console.log(`Setting status to $status`);
response.status(status).json(exception.message);




3) Instead of setting the response throw the according exception in your interceptor:



@Injectable()
export class StatusInterceptor implements NestInterceptor
intercept(context: ExecutionContext, next): Observable<any>
return next.handle().pipe(
map((data: any) =>
if (data.text === 'created')
throw new StatusException(data, HttpStatus.CREATED);
else
throw new StatusException(data, HttpStatus.ACCEPTED);

),
);




4) Use it in your controller:



@UseFilters(StatusFilter)
@UseInterceptors(StatusInterceptor)
@Controller()
export class AppController
@Get(':param')
async get(@Param('param') param)
return text: param ;





Alternatively, you can inject @Res() in your controller and directly control the response code (but also losing interceptors, exception filters, etc.)






share|improve this answer



























  • thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

    – toonvanstrijp
    Mar 31 at 10:42











  • According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

    – Felipe Issa
    Jul 17 at 16:49











  • I'm the creator of the PR ;) but thanks for your work around! :D

    – toonvanstrijp
    Aug 19 at 16:55











  • Haha, sorry, didn't see that. Thanks for the PR! :-)

    – Kim Kern
    Aug 19 at 16:57












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406194%2fnestjs-set-httpstatus-in-interceptor%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1
















Updated Answer



Since nest version 6.1.0, it is possible to set the status code in an interceptor; it will not be overwritten anymore (see this PR):



context.switchToHttp()
.getResponse()
.status(205);



Outdated Answer



Setting the status code from an Interceptor is impossible (see this issue) because:




  • sometimes response status codes are dependent on exceptions and exception filters are executed after interceptors,

  • global response controller's logic is the last step performed just before sending a final result through the network (that's the place
    where default status codes come in).



So your status code will be overridden by the default code 200/201 or an exception filter.




As a (hacky) workaround, you can use exception filters to set the status code in interceptors:



1) Create your own exception as a wrapper around HttpException:



export class StatusException extends HttpException 
constructor(data, status: HttpStatus)
super(data, status);




2) Create an exception filter that sets the response code and returns the data:



@Catch(StatusException)
export class StatusFilter implements ExceptionFilter
catch(exception: StatusException, host: ArgumentsHost)
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
console.log(`Setting status to $status`);
response.status(status).json(exception.message);




3) Instead of setting the response throw the according exception in your interceptor:



@Injectable()
export class StatusInterceptor implements NestInterceptor
intercept(context: ExecutionContext, next): Observable<any>
return next.handle().pipe(
map((data: any) =>
if (data.text === 'created')
throw new StatusException(data, HttpStatus.CREATED);
else
throw new StatusException(data, HttpStatus.ACCEPTED);

),
);




4) Use it in your controller:



@UseFilters(StatusFilter)
@UseInterceptors(StatusInterceptor)
@Controller()
export class AppController
@Get(':param')
async get(@Param('param') param)
return text: param ;





Alternatively, you can inject @Res() in your controller and directly control the response code (but also losing interceptors, exception filters, etc.)






share|improve this answer



























  • thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

    – toonvanstrijp
    Mar 31 at 10:42











  • According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

    – Felipe Issa
    Jul 17 at 16:49











  • I'm the creator of the PR ;) but thanks for your work around! :D

    – toonvanstrijp
    Aug 19 at 16:55











  • Haha, sorry, didn't see that. Thanks for the PR! :-)

    – Kim Kern
    Aug 19 at 16:57















1
















Updated Answer



Since nest version 6.1.0, it is possible to set the status code in an interceptor; it will not be overwritten anymore (see this PR):



context.switchToHttp()
.getResponse()
.status(205);



Outdated Answer



Setting the status code from an Interceptor is impossible (see this issue) because:




  • sometimes response status codes are dependent on exceptions and exception filters are executed after interceptors,

  • global response controller's logic is the last step performed just before sending a final result through the network (that's the place
    where default status codes come in).



So your status code will be overridden by the default code 200/201 or an exception filter.




As a (hacky) workaround, you can use exception filters to set the status code in interceptors:



1) Create your own exception as a wrapper around HttpException:



export class StatusException extends HttpException 
constructor(data, status: HttpStatus)
super(data, status);




2) Create an exception filter that sets the response code and returns the data:



@Catch(StatusException)
export class StatusFilter implements ExceptionFilter
catch(exception: StatusException, host: ArgumentsHost)
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
console.log(`Setting status to $status`);
response.status(status).json(exception.message);




3) Instead of setting the response throw the according exception in your interceptor:



@Injectable()
export class StatusInterceptor implements NestInterceptor
intercept(context: ExecutionContext, next): Observable<any>
return next.handle().pipe(
map((data: any) =>
if (data.text === 'created')
throw new StatusException(data, HttpStatus.CREATED);
else
throw new StatusException(data, HttpStatus.ACCEPTED);

),
);




4) Use it in your controller:



@UseFilters(StatusFilter)
@UseInterceptors(StatusInterceptor)
@Controller()
export class AppController
@Get(':param')
async get(@Param('param') param)
return text: param ;





Alternatively, you can inject @Res() in your controller and directly control the response code (but also losing interceptors, exception filters, etc.)






share|improve this answer



























  • thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

    – toonvanstrijp
    Mar 31 at 10:42











  • According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

    – Felipe Issa
    Jul 17 at 16:49











  • I'm the creator of the PR ;) but thanks for your work around! :D

    – toonvanstrijp
    Aug 19 at 16:55











  • Haha, sorry, didn't see that. Thanks for the PR! :-)

    – Kim Kern
    Aug 19 at 16:57













1














1










1









Updated Answer



Since nest version 6.1.0, it is possible to set the status code in an interceptor; it will not be overwritten anymore (see this PR):



context.switchToHttp()
.getResponse()
.status(205);



Outdated Answer



Setting the status code from an Interceptor is impossible (see this issue) because:




  • sometimes response status codes are dependent on exceptions and exception filters are executed after interceptors,

  • global response controller's logic is the last step performed just before sending a final result through the network (that's the place
    where default status codes come in).



So your status code will be overridden by the default code 200/201 or an exception filter.




As a (hacky) workaround, you can use exception filters to set the status code in interceptors:



1) Create your own exception as a wrapper around HttpException:



export class StatusException extends HttpException 
constructor(data, status: HttpStatus)
super(data, status);




2) Create an exception filter that sets the response code and returns the data:



@Catch(StatusException)
export class StatusFilter implements ExceptionFilter
catch(exception: StatusException, host: ArgumentsHost)
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
console.log(`Setting status to $status`);
response.status(status).json(exception.message);




3) Instead of setting the response throw the according exception in your interceptor:



@Injectable()
export class StatusInterceptor implements NestInterceptor
intercept(context: ExecutionContext, next): Observable<any>
return next.handle().pipe(
map((data: any) =>
if (data.text === 'created')
throw new StatusException(data, HttpStatus.CREATED);
else
throw new StatusException(data, HttpStatus.ACCEPTED);

),
);




4) Use it in your controller:



@UseFilters(StatusFilter)
@UseInterceptors(StatusInterceptor)
@Controller()
export class AppController
@Get(':param')
async get(@Param('param') param)
return text: param ;





Alternatively, you can inject @Res() in your controller and directly control the response code (but also losing interceptors, exception filters, etc.)






share|improve this answer















Updated Answer



Since nest version 6.1.0, it is possible to set the status code in an interceptor; it will not be overwritten anymore (see this PR):



context.switchToHttp()
.getResponse()
.status(205);



Outdated Answer



Setting the status code from an Interceptor is impossible (see this issue) because:




  • sometimes response status codes are dependent on exceptions and exception filters are executed after interceptors,

  • global response controller's logic is the last step performed just before sending a final result through the network (that's the place
    where default status codes come in).



So your status code will be overridden by the default code 200/201 or an exception filter.




As a (hacky) workaround, you can use exception filters to set the status code in interceptors:



1) Create your own exception as a wrapper around HttpException:



export class StatusException extends HttpException 
constructor(data, status: HttpStatus)
super(data, status);




2) Create an exception filter that sets the response code and returns the data:



@Catch(StatusException)
export class StatusFilter implements ExceptionFilter
catch(exception: StatusException, host: ArgumentsHost)
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
console.log(`Setting status to $status`);
response.status(status).json(exception.message);




3) Instead of setting the response throw the according exception in your interceptor:



@Injectable()
export class StatusInterceptor implements NestInterceptor
intercept(context: ExecutionContext, next): Observable<any>
return next.handle().pipe(
map((data: any) =>
if (data.text === 'created')
throw new StatusException(data, HttpStatus.CREATED);
else
throw new StatusException(data, HttpStatus.ACCEPTED);

),
);




4) Use it in your controller:



@UseFilters(StatusFilter)
@UseInterceptors(StatusInterceptor)
@Controller()
export class AppController
@Get(':param')
async get(@Param('param') param)
return text: param ;





Alternatively, you can inject @Res() in your controller and directly control the response code (but also losing interceptors, exception filters, etc.)







share|improve this answer














share|improve this answer



share|improve this answer








edited Aug 4 at 15:57

























answered Mar 29 at 0:34









Kim KernKim Kern

15.9k6 gold badges43 silver badges70 bronze badges




15.9k6 gold badges43 silver badges70 bronze badges















  • thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

    – toonvanstrijp
    Mar 31 at 10:42











  • According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

    – Felipe Issa
    Jul 17 at 16:49











  • I'm the creator of the PR ;) but thanks for your work around! :D

    – toonvanstrijp
    Aug 19 at 16:55











  • Haha, sorry, didn't see that. Thanks for the PR! :-)

    – Kim Kern
    Aug 19 at 16:57

















  • thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

    – toonvanstrijp
    Mar 31 at 10:42











  • According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

    – Felipe Issa
    Jul 17 at 16:49











  • I'm the creator of the PR ;) but thanks for your work around! :D

    – toonvanstrijp
    Aug 19 at 16:55











  • Haha, sorry, didn't see that. Thanks for the PR! :-)

    – Kim Kern
    Aug 19 at 16:57
















thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

– toonvanstrijp
Mar 31 at 10:42





thanks. This will do it for now, but still it’s not a good solution since the middleware/interceptors provided later on won’t run anymore. Think I’ll make a pull request to the framework with some changes that allows the user to set the status code freely. But thanks for those work arounds.

– toonvanstrijp
Mar 31 at 10:42













According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

– Felipe Issa
Jul 17 at 16:49





According to the exception filter documentation, the 'HttpException' is treated by default, so you simple need to throw it with the return status you want on your interceptor and it will work.

– Felipe Issa
Jul 17 at 16:49













I'm the creator of the PR ;) but thanks for your work around! :D

– toonvanstrijp
Aug 19 at 16:55





I'm the creator of the PR ;) but thanks for your work around! :D

– toonvanstrijp
Aug 19 at 16:55













Haha, sorry, didn't see that. Thanks for the PR! :-)

– Kim Kern
Aug 19 at 16:57





Haha, sorry, didn't see that. Thanks for the PR! :-)

– Kim Kern
Aug 19 at 16:57




















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406194%2fnestjs-set-httpstatus-in-interceptor%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해