NestJS中ContentTypeInterceptor集成nestjs-i18n失效问题排查
问题:NestJS拦截器中无法通过nestjs-i18n获取本地化上下文返回提示信息
我创建了一个ContentTypeInterceptor拦截器,目的是当请求违反content-type规则时,通过nestjs-i18n返回本地化的提示信息,但编写如下代码后无法正常工作:
'use strict' import { CallHandler, ExecutionContext, NestInterceptor, UnsupportedMediaTypeException } from '@nestjs/common' import { Request } from 'express' import { I18nContext, I18nTranslation } from 'nestjs-i18n' export class ContentTypeInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler) { const i18n: any = I18nContext.current<I18nTranslation>(next) console.log('i18n:',i18n?.t('lang.HELLO')) const request = context.switchToHttp().getRequest<Request>() if (this.hasBody(request.method) && !request.is('json')) { throw new UnsupportedMediaTypeException(i18n?.t('lang.GENERIC.UNSUPPORTED_MEDIA_TYPE_MESSAGE')) } return next.handle() } private hasBody(httpMethod: string): boolean { return ['POST', 'PUT', 'PATCH'].includes(httpMethod) } }
解决方案
问题出在获取I18nContext的方式上:原代码错误地将CallHandler类型的next传入I18nContext.current(),而该方法需要的参数是ExecutionContext。
修改后的拦截器代码如下:
'use strict' import { CallHandler, ExecutionContext, NestInterceptor, UnsupportedMediaTypeException } from '@nestjs/common' import { Request } from 'express' import { I18nContext, I18nTranslation } from 'nestjs-i18n' export class ContentTypeInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler) { // 关键改动:从ExecutionContext获取I18n上下文 const i18n = I18nContext.current<I18nTranslation>(context) console.log('i18n:',i18n?.t('lang.HELLO')) const request = context.switchToHttp().getRequest<Request>() if (this.hasBody(request.method) && !request.is('json')) { // 兜底逻辑:避免i18n上下文获取失败时无提示 const message = i18n?.t('lang.GENERIC.UNSUPPORTED_MEDIA_TYPE_MESSAGE') || '不支持的媒体类型' throw new UnsupportedMediaTypeException(message) } return next.handle() } private hasBody(httpMethod: string): boolean { return ['POST', 'PUT', 'PATCH'].includes(httpMethod) } }
关键说明
- 正确获取上下文:
I18nContext.current(context)会从当前请求的上下文环境中读取本地化信息,这是符合nestjs-i18n设计的正确调用方式。 - 添加兜底提示:增加默认文本,防止因i18n上下文异常导致返回空提示的问题。
内容的提问来源于stack exchange,提问作者Shubham Verma
相关产品推荐
相关产品推荐

