Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: validator throws error rathar than return c.json() #2021

Merged
merged 2 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 5 additions & 23 deletions deno_dist/validator/validator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Context } from '../context.ts'
import { getCookie } from '../helper/cookie/index.ts'
import { HTTPException } from '../http-exception.ts'
import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types.ts'
import type { BodyData } from '../utils/body.ts'
import { bufferToFormData } from '../utils/buffer.ts'
Expand Down Expand Up @@ -55,14 +56,7 @@ export const validator = <
case 'json':
if (!contentType || !contentType.startsWith('application/json')) {
const message = `Invalid HTTP header: Content-Type=${contentType}`
console.error(message)
return c.json(
{
success: false,
message,
},
400
)
throw new HTTPException(400, { message })
}
/**
* Get the arrayBuffer first, create JSON object via Response,
Expand All @@ -74,14 +68,8 @@ export const validator = <
c.req.bodyCache.json = value
c.req.bodyCache.arrayBuffer = arrayBuffer
} catch {
console.error('Error: Malformed JSON in request body')
return c.json(
{
success: false,
message: 'Malformed JSON in request body',
},
400
)
const message = 'Malformed JSON in request body'
throw new HTTPException(400, { message })
}
break
case 'form': {
Expand All @@ -101,13 +89,7 @@ export const validator = <
} catch (e) {
let message = 'Malformed FormData request.'
message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`
return c.json(
{
success: false,
message,
},
400
)
throw new HTTPException(400, { message })
}
break
}
Expand Down
13 changes: 11 additions & 2 deletions src/validator/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import type { ZodSchema } from 'zod'
import { z } from 'zod'
import { Hono } from '../hono'
import type { ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'
import { HTTPException } from '../http-exception'
import type { ErrorHandler, ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'
import type { Equal, Expect } from '../utils/types'
import type { ValidationFunction } from './validator'
import { validator } from './validator'
Expand Down Expand Up @@ -75,16 +76,23 @@ describe('Validator middleware', () => {
})
})

const onErrorHandler: ErrorHandler = (e, c) => {
if (e instanceof HTTPException) {
return c.json({ message: e.message, success: false }, e.status)
}
return c.json({ message: e.message }, 500)
}

describe('Malformed JSON', () => {
const app = new Hono()

app.post(
'/post',
validator('json', (value, c) => {}),
(c) => {
return c.text('Valid!')
}
)
app.onError(onErrorHandler)

it('Should return 400 response', async () => {
const res = await app.request('http://localhost/post', {
Expand Down Expand Up @@ -133,6 +141,7 @@ describe('Malformed FormData request', () => {
return c.text('Valid!')
}
)
app.onError(onErrorHandler)

it('Should return 400 response, for unsupported content type header', async () => {
const res = await app.request('http://localhost/post', {
Expand Down
28 changes: 5 additions & 23 deletions src/validator/validator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Context } from '../context'
import { getCookie } from '../helper/cookie'
import { HTTPException } from '../http-exception'
import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types'
import type { BodyData } from '../utils/body'
import { bufferToFormData } from '../utils/buffer'
Expand Down Expand Up @@ -55,14 +56,7 @@ export const validator = <
case 'json':
if (!contentType || !contentType.startsWith('application/json')) {
const message = `Invalid HTTP header: Content-Type=${contentType}`
console.error(message)
return c.json(
{
success: false,
message,
},
400
)
throw new HTTPException(400, { message })
}
/**
* Get the arrayBuffer first, create JSON object via Response,
Expand All @@ -74,14 +68,8 @@ export const validator = <
c.req.bodyCache.json = value
c.req.bodyCache.arrayBuffer = arrayBuffer
} catch {
console.error('Error: Malformed JSON in request body')
return c.json(
{
success: false,
message: 'Malformed JSON in request body',
},
400
)
const message = 'Malformed JSON in request body'
throw new HTTPException(400, { message })
}
break
case 'form': {
Expand All @@ -101,13 +89,7 @@ export const validator = <
} catch (e) {
let message = 'Malformed FormData request.'
message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`
return c.json(
{
success: false,
message,
},
400
)
throw new HTTPException(400, { message })
}
break
}
Expand Down