- renamings to the new naming convetion for adonisjs version 6
Some checks failed
CI Pipeline / japa-tests (push) Failing after 58s

- npm updates
This commit is contained in:
Kaimbacher 2024-04-29 11:25:50 +02:00
parent bee76f8d5b
commit a29865b781
53 changed files with 701 additions and 731 deletions

View file

@ -0,0 +1,12 @@
class DoiClientException extends Error {
public status: number;
public message: string;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
}
}
export default DoiClientException;

View file

@ -0,0 +1,12 @@
class HTTPException extends Error {
public status: number;
public message: string;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
}
}
export default HTTPException;

View file

@ -0,0 +1,10 @@
import { StatusCodes } from 'http-status-codes';
import HTTPException from './HttpException.js';
class InternalServerErrorException extends HTTPException {
constructor(message?: string) {
super(StatusCodes.INTERNAL_SERVER_ERROR, message || 'Server Error');
this.stack = '';
}
}
export default InternalServerErrorException;

View file

@ -0,0 +1,69 @@
import { Exception } from "@adonisjs/core/exceptions";
import { HttpContext } from "@adonisjs/core/http";
/*
|--------------------------------------------------------------------------
| Exception
|--------------------------------------------------------------------------
|
| The Exception class imported from '@adonisjs/core' allows defining
| a status code and error code for every exception.
|
| @example
| new InvalidCredentialException('message', 403, 'E_RUNTIME_EXCEPTION')
|
*/
export default class InvalidCredentialException extends Exception {
// constructor() {
// super(...arguments);
// // this.responseText = this.message;
// }
/**
* Unable to find user
*/
public static invalidUid() {
const error = new this('User not found', {status: 400, code: 'E_INVALID_AUTH_UID'});
return error;
}
/**
* Invalid user password
*/
public static invalidPassword() {
const error = new this('Password mis-match', {status: 400, code: 'E_INVALID_AUTH_PASSWORD'});
return error;
}
/**
* Flash error message and redirect the user back
*/
private respondWithRedirect(error: any, ctx: HttpContext) {
// if (!ctx.session) {
// return ctx.response.status(this.status).send(this.responseText);
// }
ctx.session.flashExcept(['_csrf']);
ctx.session.flash('auth', {
error: error,
/**
* Will be removed in the future
*/
errors: {
uid: this.code === 'E_INVALID_AUTH_UID' ? ['Invalid login id'] : null,
password: this.code === 'E_INVALID_AUTH_PASSWORD' ? ['Invalid password'] : null,
},
});
ctx.response.redirect('back', true);
}
/**
* Handle this exception by itself
*/
public handle(error: any, ctx: HttpContext) {
// return response.status(403).view.render("errors/unauthorized", {
// error: error,
// });
this.respondWithRedirect(error, ctx);
}
}

View file

@ -0,0 +1,48 @@
export enum OaiErrorCodes {
BADVERB = 1010,
BADARGUMENT = 1011,
CANNOTDISSEMINATEFORMAT = 1012,
BADRESUMPTIONTOKEN = 1013,
NORECORDSMATCH = 1014,
IDDOESNOTEXIST = 1015,
}
// 👇️ default export
// export { OaiErrorCodes };
// https://medium.com/@juliapassynkova/map-your-typescript-enums-e402d406b229
export const OaiModelError = new Map<number, string>([
[OaiErrorCodes.BADVERB, 'badVerb'],
[OaiErrorCodes.BADARGUMENT, 'badArgument'],
[OaiErrorCodes.NORECORDSMATCH, 'noRecordsMatch'],
[OaiErrorCodes.CANNOTDISSEMINATEFORMAT, 'cannotDisseminateFormat'],
[OaiErrorCodes.BADRESUMPTIONTOKEN, 'badResumptionToken'],
[OaiErrorCodes.IDDOESNOTEXIST, 'idDoesNotExist'],
]);
// class OaiModelError {
// // const BADVERB = 1010;
// // const BADARGUMENT = 1011;
// // const CANNOTDISSEMINATEFORMAT = 1012;
// // const BADRESUMPTIONTOKEN = 1013;
// // const NORECORDSMATCH = 1014;
// // const IDDOESNOTEXIST = 1015;
// protected static $oaiErrorCodes = {
// OaiErrorCodes. 'badVerb',
// BADARGUMENT : 'badArgument',
// NORECORDSMATCH: 'noRecordsMatch',
// CANNOTDISSEMINATEFORMAT: 'cannotDisseminateFormat',
// BADRESUMPTIONTOKEN: 'badResumptionToken',
// IDDOESNOTEXIST: 'idDoesNotExist',
// };
// public static function mapCode($code)
// {
// if (false === array_key_exists($code, self::$oaiErrorCodes)) {
// throw new OaiModelException("Unknown oai error code $code");
// }
// return self::$oaiErrorCodes[$code];
// }
// }

View file

@ -0,0 +1,77 @@
import { StatusCodes } from 'http-status-codes';
// import HTTPException from './HttpException';
import { OaiErrorCodes } from './OaiErrorCodes.js';
export class ErrorCode {
public static readonly Unauthenticated = 'Unauthenticated';
public static readonly NotFound = 'NotFound';
public static readonly MaximumAllowedGrade = 'MaximumAllowedGrade';
public static readonly AsyncError = 'AsyncError';
public static readonly UnknownError = 'UnknownError';
}
export class ErrorModel {
/**
* Unique error code which identifies the error.
*/
public code: string;
/**
* Status code of the error.
*/
public status: number;
/**
* Any additional data that is required for translation.
*/
// public metaData?: any;
}
export class OaiModelException extends Error {
public status: number;
public message: string;
public oaiCode: number;
// constructor(status: number, message: string) {
// super(message);
// this.status = status;
// this.message = message;
// }
constructor(status: number, message: string, oaiCode: number) {
super(message);
this.status = status;
this.message = message;
this.oaiCode = oaiCode;
}
// constructor(code: string = ErrorCode.UnknownError, message: any = null) {
// super(code);
// Object.setPrototypeOf(this, new.target.prototype);
// this.name = code;
// this.status = 500;
// this.message = message;
// // switch (code) {
// // case ErrorCode.Unauthenticated:
// // this.status = 401;
// // break;
// // case ErrorCode.MaximumAllowedGrade:
// // this.status = 400;
// // break;
// // case ErrorCode.AsyncError:
// // this.status = 400;
// // break;
// // case ErrorCode.NotFound:
// // this.status = 404;
// // break;
// // default:
// // this.status = 500;
// // break;
// // }
// }
}
export class BadOaiModelException extends OaiModelException {
constructor(message?: string) {
super(StatusCodes.INTERNAL_SERVER_ERROR, message || 'bad Request', OaiErrorCodes.BADARGUMENT);
this.stack = '';
}
}
// export default OaiModelexception;

125
app/exceptions/handler.ts Normal file
View file

@ -0,0 +1,125 @@
/*
|--------------------------------------------------------------------------
| Http Exception Handler
|--------------------------------------------------------------------------
|
| AdonisJs will forward all exceptions occurred during an HTTP request to
| the following class. You can learn more about exception handling by
| reading docs.
|
| The exception handler extends a base `HttpExceptionHandler` which is not
| mandatory, however it can do lot of heavy lifting to handle the errors
| properly.
|
*/
import app from '@adonisjs/core/services/app';
import { HttpContext, ExceptionHandler } from '@adonisjs/core/http';
// import logger from '@adonisjs/core/services/logger';
import type { StatusPageRange, StatusPageRenderer } from '@adonisjs/core/types/http';
export default class HttpExceptionHandler extends ExceptionHandler {
/**
* In debug mode, the exception handler will display verbose errors
* with pretty printed stack traces.
*/
protected debug = !app.inProduction;
/**
* Status pages are used to display a custom HTML pages for certain error
* codes. You might want to enable them in production only, but feel
* free to enable them in development as well.
*/
protected renderStatusPages = true; //app.inProduction;
/**
* Status pages is a collection of error code range and a callback
* to return the HTML contents to send as a response.
*/
// protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {
// '401..403': (error, { view }) => {
// return view.render('./errors/unauthorized', { error });
// },
// '404': (error, { view }) => {
// return view.render('./errors/not-found', { error });
// },
// '500..599': (error, { view }) => {
// return view.render('./errors/server-error', { error });
// },
// };
protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {
'404': (error, { inertia }) => {
return inertia.render('Errors/ServerError', {
error: error.message,
code: error.status,
});
},
'401..403': async (error, { inertia }) => {
// session.flash('errors', error.message);
return inertia.render('Errors/ServerError', {
error: error.message,
code: error.status,
});
},
'500..599': (error, { inertia }) => inertia.render('Errors/ServerError', { error: error.message, code: error.status }),
};
// constructor() {
// super(logger);
// }
public async handle(error: any, ctx: HttpContext) {
const { response, request, session, inertia } = ctx;
/**
* Handle failed authentication attempt
*/
// if (['E_INVALID_AUTH_PASSWORD', 'E_INVALID_AUTH_UID'].includes(error.code)) {
// session.flash('errors', { login: error.message });
// return response.redirect('/login');
// }
// if ([401].includes(error.status)) {
// session.flash('errors', { login: error.message });
// return response.redirect('/dashboard');
// }
// https://github.com/inertiajs/inertia-laravel/issues/56
// let test = response.getStatus(); //200
// let header = request.header('X-Inertia'); // true
// if (request.header('X-Inertia') && [500, 503, 404, 403, 401, 200].includes(response.getStatus())) {
if (request.header('X-Inertia') && [422].includes(error.status)) {
// session.flash('errors', error.messages.errors);
session.flash('errors', error.messages);
return response.redirect().back();
// return inertia.render('errors/server_error', {
// return inertia.render('errors/server_error', {
// // status: response.getStatus(),
// error: error,
// });
// ->toResponse($request)
// ->setStatusCode($response->status());
}
// Dynamically change the error templates based on the absence of X-Inertia header
// if (!ctx.request.header('X-Inertia')) {
// this.statusPages = {
// '401..403': (error, { view }) => view.render('./errors/unauthorized', { error }),
// '404': (error, { view }) => view.render('./errors/not-found', { error }),
// '500..599': (error, { view }) => view.render('./errors/server-error', { error }),
// };
// }
/**
* Forward rest of the exceptions to the parent class
*/
return super.handle(error, ctx);
}
/**
* The method is used to report error to the logging service or
* the a third party error monitoring service.
*
* @note You should not attempt to send a response from this method.
*/
async report(error: unknown, ctx: HttpContext) {
return super.report(error, ctx);
}
}