fix: throw clear error on invalid LOG_LEVELS (#18495)

Fixes #18356

## Summary

Setting `LOG_LEVELS=debug,info,error,warn` crashes with `TypeError:
logLevels.map is not a function` because `CastToLogLevelArray` silently
returns `undefined` for invalid levels.

Now it throws a clear error message listing the invalid levels and valid
options:

```
Invalid log level(s): info. Valid levels are: log, error, warn, debug, verbose
```

## Changes

- Throw descriptive `Error` when invalid log levels are provided instead
of returning `undefined`
- Updated tests to verify the error message

## Test plan

- [x] All 8 existing tests passing
- [x] `"toto"` → throws `Invalid log level(s): toto. Valid levels are:
log, error, warn, debug, verbose`
- [x] `"verbose,error,toto"` → throws listing only `toto` as invalid
- [x] Valid levels (`log,error,warn,debug,verbose`) continue working as
before
This commit is contained in:
Felipe
2026-03-09 12:41:15 -03:00
committed by GitHub
parent 75bb3a904d
commit 5ab3eeb830
2 changed files with 20 additions and 14 deletions
@@ -50,17 +50,17 @@ describe('CastToLogLevelArray Decorator', () => {
]);
});
it('should cast "toto" to undefined', () => {
const transformedClass = plainToClass(TestClass, { logLevels: 'toto' });
expect(transformedClass.logLevels).toBeUndefined();
it('should throw on invalid level "toto" with clear error message', () => {
expect(() => plainToClass(TestClass, { logLevels: 'toto' })).toThrow(
'Invalid log level(s): toto. Valid levels are: log, error, warn, debug, verbose',
);
});
it('should cast "verbose,error,toto" to undefined', () => {
const transformedClass = plainToClass(TestClass, {
logLevels: 'verbose,error,toto',
});
expect(transformedClass.logLevels).toBeUndefined();
it('should throw on "verbose,error,toto" listing only invalid levels', () => {
expect(() =>
plainToClass(TestClass, { logLevels: 'verbose,error,toto' }),
).toThrow(
'Invalid log level(s): toto. Valid levels are: log, error, warn, debug, verbose',
);
});
});
@@ -1,5 +1,7 @@
import { Transform } from 'class-transformer';
const VALID_LOG_LEVELS = ['log', 'error', 'warn', 'debug', 'verbose'];
export const CastToLogLevelArray = () =>
Transform(({ value }: { value: string }) => toLogLevelArray(value));
@@ -7,13 +9,17 @@ export const CastToLogLevelArray = () =>
const toLogLevelArray = (value: any) => {
if (typeof value === 'string') {
const rawLogLevels = value.split(',').map((level) => level.trim());
const isInvalid = rawLogLevels.some(
(level) => !['log', 'error', 'warn', 'debug', 'verbose'].includes(level),
const invalidLevels = rawLogLevels.filter(
(level) => !VALID_LOG_LEVELS.includes(level),
);
if (!isInvalid) {
return rawLogLevels;
if (invalidLevels.length > 0) {
throw new Error(
`Invalid log level(s): ${invalidLevels.join(', ')}. Valid levels are: ${VALID_LOG_LEVELS.join(', ')}`,
);
}
return rawLogLevels;
}
return undefined;