"use strict";
/*
 * @adonisjs/validator
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationException = void 0;
const utils_1 = require("@poppinss/utils");
/**
 * Validation exception raised by the error reporters. The handle method is called
 * automatically during an HTTP request by AdonisJS to self handle the exception
 */
class ValidationException extends utils_1.Exception {
    constructor(flashToSession, messages) {
        super('Validation Exception', 422, 'E_VALIDATION_FAILURE');
        this.flashToSession = flashToSession;
        this.messages = messages;
    }
    /**
     * Handle exception.
     */
    async handle(error, ctx) {
        /**
         * Return the error messages as it is when `flashToSession` is explicitly disabled
         * or session module is not installed
         */
        if (!error.flashToSession || !ctx['session']) {
            return ctx.response.status(error.status).send(error.messages);
        }
        const session = ctx['session'];
        /**
         * Flash all input, except the `_csrf`.
         */
        session.flashExcept(['_csrf', '_method']);
        /**
         * Flash errors
         */
        ctx['session'].flash('errors', error.messages);
        /**
         * Redirect back with the query string
         */
        ctx.response.redirect('back', true);
    }
}
exports.ValidationException = ValidationException;
