Extending Angular ExceptionHandler, types not comparing - exception

I have this simple class:
export class MyError extends Error {}
export class AnotherError extends Error {}
export class CustomExceptionHandler implements ExceptionHandler {
call(exception: any, stackTrace = null, reason = null) {
if (exception instanceof MyError) {
console.log("Here is MyError error");
}
}
}
I throw an error somewhere in the code:
throw new MyError()
Nevertheless the console.log never appears. The if statement is not satisfied. I want to be able to throw custom errors and handle them based on type. Why isn't this working?
The output of console.log(exception) is:
ViewWrappedException {
_wrapperMessage: "Error in ./CenterOnMeButton class CenterOnMeButton - inline template:0:28",
_originalException: MyError,
_originalStack: undefined,
_context: DebugContext,
_wrapperStack: "Error: Error in ./CenterOnMeButton class CenterOnM…tp://localhost:3000/polyfills.bundle.js:14981:35)"…
}
_context: DebugContext
_originalException: MyError
_originalStack: undefined
_wrapperMessage: "Error in ./CenterOnMeButton class CenterOnMeButton - inline template:0:28"
_wrapperStack: "Error: Error in ./CenterOnMeButton class CenterOnMeButton - inline template:0:28
at ViewWrappedException.WrappedException [as constructor] (http://localhost:3000/vendor.bundle.js:2025:32)
at new ViewWrappedException (http://localhost:3000/vendor.bundle.js:20847:17)
at DebugAppView._rethrowWithContext (http://localhost:3000/vendor.bundle.js:42584:24)
at http://localhost:3000/vendor.bundle.js:42597:24
at http://localhost:3000/vendor.bundle.js:34994:37
at http://localhost:3000/vendor.bundle.js:35057:94
at ZoneDelegate.invoke (http://localhost:3000/polyfills.bundle.js:14881:30)
at Object.onInvoke (http://localhost:3000/vendor.bundle.js:33274:42)
at ZoneDelegate.invoke (http://localhost:3000/polyfills.bundle.js:14880:36)
at Zone.runGuarded (http://localhost:3000/polyfills.bundle.js:14788:49)
at NgZoneImpl.runInnerGuarded (http://localhost:3000/vendor.bundle.js:33307:79)
at NgZone.runGuarded (http://localhost:3000/vendor.bundle.js:21420:74)
at HTMLDivElement.outsideHandler (http://localhost:3000/vendor.bundle.js:35057:62)
at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:14914:39)
at Zone.runTask (http://localhost:3000/polyfills.bundle.js:14814:49)
at HTMLDivElement.ZoneTask.invoke (http://localhost:3000/polyfills.bundle.js:14981:35)"
context

Related

semantic error TS2574: A rest element type must be an array type

Here is the code src/object.ts(50,58)
interface sanitizer<T> {
(val: T): T
}
type MapSanitizor<T extends any[]> = T extends [infer P, ...(infer R)]
? [sanitizer<P>, ...MapSanitizor<R>]
: [];
function isArrayAs<T extends any[]>(fn: MapSanitizor<T>): sanitizer<T> {
return function(val) {
if (!Array.isArray(val))
throw new Error(`
obj val \n
= ${JSON.stringify(val)} \n
is invalid value,\n
value passed in isArrayAs is not an array
`);
const newlist: T = [] as any;
for (let i = 0; i < fn.length; i++) {
newlist.push((fn[i] as any)(val[i]));
}
return newlist;
};
}
I am trying to build my package
it given me this error when i run npm run build
Error: D:/packages/npm/sanitize-json/src/object.ts(50,58): semantic error TS2574: A rest element type must be an array type.
at error (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:5400:30)
at throwPluginError (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:11878:12)
at Object.error (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:12912:24)
at Object.error (D:\packages\npm\sanitize-json\node_modules\rollup\dist\shared\node-entry.js:12081:38)
at RollupContext.error (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:17237:30)
at D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:25033:23
at arrayEach (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:545:11)
at Function.forEach (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:9397:14)
at printDiagnostics (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:25006:12)
at Object.transform (D:\packages\npm\sanitize-json\node_modules\rollup-plugin-typescript2\dist\rollup-plugin-typescript2.cjs.js:29277:17)
what have i done wrong? i dont see any error popup in vscode compiler.

Laravel 8 Handler Undefined class 'Exception'

I work in API Laravel project and try to handler
"message": "No query results for model ID"
and page 404
I use this function but don't send anything in API and no effect on 404 pages
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler
{
public function render($request, Exception $e)
{
// "message": "No query results for model ID" in API
if ($e instanceof ModelNotFoundException) {
return response()->json(['error' => 'Data not found.']);
}
if($this->isHttpException($e))
{
switch ($e->getStatusCode())
{
// not found
case 404:
return redirect()->guest('home');
break;
// internal error
case '500':
return redirect()->guest('home');
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
}
}
Use Throwable not Exception
public function render($request, Throwable $e)
{
// "message": "No query results for model ID" in API
if ($e instanceof ModelNotFoundException) {
return response()->json(['error' => 'Data not found.']);
}
return parent::render($request, $e);
}

Why am I getting an error when trying to call a method with flutter chopper and built value?

I'm getting The below ERROR,I believe it's because of null safety, this means that no data has been received or getSignedInUser() method is incorrect or class BuiltValueConverter is the cause.
(I tested the token with Postman and retrieved the data)
E/flutter (21792): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: Unhandled error Null check operator used on a
null value occurred in Instance of 'AuthBloc'. E/flutter (21792): #0
BuiltValueConverter._deserialize
package:todo_list_app/…/auth/built_value_converter.dart:51 E/flutter
(21792): #1 BuiltValueConverter._convertToCustomObject
package:todo_list_app/…/auth/built_value_converter.dart:36 E/flutter
(21792): #2 BuiltValueConverter.convertResponse
package:todo_list_app/…/auth/built_value_converter.dart:25
I'm using chopper with built_value Pubs. i'm trying to convert the coming json to object.
Example:
{
"userName": "Jack",
"email": "jack2066#gmail.com",
"userRole": "USER",
"created_at": "2021-07-03T16:49:56.774Z",
"updated_at": "2021-07-03T16:49:56.774Z" }
the below code where the error start also explained in this Tutorial Converters & Built Value Integration
import 'package:built_collection/built_collection.dart';
import 'package:chopper/chopper.dart';
import 'package:todo_list_app/infrastructure/remote/auth/models/serializers.dart';
class BuiltValueConverter extends JsonConverter {
#override
Request convertRequest(Request request) {
return super.convertRequest(
request.copyWith(
body: serializers.serializeWith(
serializers.serializerForType(request.body.runtimeType)!,
request.body,
),
),
);
}
#override
Response<BodyType> convertResponse<BodyType, SingleItemType>(
Response response,
) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody =
_convertToCustomObject<SingleItemType>(dynamicResponse.body);//
return dynamicResponse.copyWith<BodyType>(body: customBody);
}
dynamic _convertToCustomObject<SingleItemType>(dynamic element) {
if (element is SingleItemType) return element;
if (element is List)
return _deserializeListOf<SingleItemType>(element);
else
return _deserialize<SingleItemType>(element);
}
BuiltList<SingleItemType> _deserializeListOf<SingleItemType>(
List dynamicList,
) {
// Make a BuiltList holding individual custom objects
return BuiltList<SingleItemType>(
dynamicList.map((element) => _deserialize<SingleItemType>(element)),
);
}
SingleItemType _deserialize<SingleItemType>(Map<String, dynamic> value,) {
// We have a type parameter for the BuiltValue type, which should be returned after deserialization.
return serializers.deserializeWith(
serializers.serializerForType(SingleItemType)!, // Error Start
value,
);
}
}
Here is my Chopper service code, getSignedInUser throw the error.
I don't know if the implementation of the getSignedInUser method is correct or not.
import 'package:chopper/chopper.dart';
import 'package:injectable/injectable.dart';
import 'package:todo_list_app/infrastructure/remote/auth/built_value_converter.dart';
import 'package:todo_list_app/infrastructure/remote/auth/models/auth_built_model.dart';
import 'package:todo_list_app/infrastructure/remote/core/constants.dart';
part 'auth_service.chopper.dart';
#singleton
#ChopperApi()
abstract class AuthService extends ChopperService {
#factoryMethod
static AuthService create() {
final client = ChopperClient(
baseUrl: AUTH_BASE_URL_External,
services: [
_$AuthService(),
],
converter: BuiltValueConverter(),
errorConverter: JsonConverter(),
interceptors: [
HttpLoggingInterceptor()
],
);
return _$AuthService(client);
}
#Post(path: '/signup')
Future<Response> signUp(#Body() RegisterRequestModel body);
#Post(path: '/signin')
Future<Response<LoginResponseModel>> singIn(#Body() LoginRequestModel body);
//headers: {AUTH_HEADER:BEARER+'authValue'}
#Get(path: '/auth', )//authValue='Bearer Token'
Future<Response<UserResponseModel>> getSignedInUser(#Header("Authorization") String authValue);//error Unhandled error Null check operator used on a null value
}
Any idea how to solve this Error?
also Is there a good documentation for Chopper or alternative pub with a good documentation?
Thanks
I think you are missing values in your "serielizers.dart" file it should be as followed :
#SerializersFor(const[RegisterRequestModel,LoginRequestModel,UserResponseModel])
final Serializers serializers =
(_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
Yeah, as you said it's because of null safety. Your _deserialize returns a non-null value whereas the serializers.deserializeWith can return a null value. Either you can change the return type to be nullable, or handle the null case for serializers.deserializeWith. If you want you can use the below BuiltValueConverter. It is from the example which they have given which is generic, with minor changes.
import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:chopper/chopper.dart';
import 'package:graphical_representation/app/serializers.dart';
class BuiltValueConverter extends JsonConverter {
T? _deserialize<T>(dynamic value) => serializers.deserializeWith<T>(
(serializers.serializerForType(T) as Serializer<T>),
value,
);
BuiltList<T> _deserializeListOf<T>(Iterable value) => BuiltList(
value.map((value) => _deserialize<T>(value)).toList(growable: false),
);
dynamic _decode<T>(entity) {
/// handle case when we want to access to Map<String, dynamic> directly
/// getResource or getMapResource
/// Avoid dynamic or unconverted value, this could lead to several issues
if (entity is T) return entity;
try {
if (entity is List) return _deserializeListOf<T>(entity);
return _deserialize<T>(entity);
} catch (e) {
print(e);
return null;
}
}
#override
Response<ResultType> convertResponse<ResultType, Item>(Response response) {
// use [JsonConverter] to decode json
final jsonRes = super.convertResponse(response);
final body = _decode<Item>(jsonRes.body);
return jsonRes.copyWith<ResultType>(body: body);
}
#override
Request convertRequest(Request request) => super.convertRequest(
request.copyWith(
body: serializers.serialize(request.body),
),
);
}

Null pointer exception creating domain object from Json

In the following code i get the nullpointer exception only in some cases and the JSON is the same every time. How to resolve this
Error
errors.GrailsExceptionResolver - NullPointerException occurred when processing request: [POST] /school/sd/
Cannot set property 'school' on null object. Stacktrace follows:
Message: Cannot set property 'school' on null object
controller
def save() {
if (!requestIsJson()) {
respondNotAcceptable()
return
}
println request.GSON
def sInstance = new School(request.GSON)
println "got here"
if (sInstance.save(flush: true)) {
respondCreated sInstance
} else {
respondUnprocessableEntity sInstance
}
def resp = RestClientHelper.createExpGroup(sInstance)
}
In order to create Grails object from JSON it's easy to use special converter.
import grails.converters.JSON
.......
class Controller {
def doSomthing = {
def myDomain = new MyDomain(JSON.parse(params.myDomain))
//Save domain object
myDomain.save(flush:true)
}
}
Grails converter reference.

Silex: error handlers for specific exception types

It it possible in Silex to use an error handler based on what exception is thrown?
I know this is possible with a single exception handler and a switch statement on the classname of the thrown exception but to me it seems the "Silex way" is cleaner, yet doesn't work.
This is how I would expect it to work
<?php
// Handle access denied errors
$app->error(function (\App\Rest\Exception\AccessDenied $e) {
$message = $e->getMessage() ?: 'Access denied!';
return new Response($message, 403);
});
// Handle Resource not found errors
$app->error(function (\App\Rest\Exception\ResourceNotFound $e) {
$message = $e->getMessage() ?: 'Resource not found!';
return new Response($message, 404);
});
// Handle other exception as 500 errors
$app->error(function (\Exception $e, $code) {
return new Response($e->getMessage(), $code);
});
Problem is that when I throw a ResourceNotFound exception in my controller, the errorhandler tied to AccessDenied is executed
Catchable fatal error: Argument 1 passed to {closure}() must be an instance of App\Rest\Exception\AccessDenied, instance of App\Rest\Exception\ResourceNotFound given
Is this achievable in another way or should I just stuff everything in the handler that works with generic Exceptions and switch on the type of exception thrown?
PS: i'm aware of the $app->abort() method but prefer working with exceptions
EDIT: This feature has now made it into Silex core!
This is currently not possible. Right now you'd have to either have a single handler with a switch statement, or many handlers with an if ($e instanceof MyException) each.
I do like the idea though, and it should be possible to implement it by using reflection. It would be awesome if you could create a new ticket on the tracker, or even work on a patch, if you're interested.
Cheers!
Another solution that I use in my projects:
class ProcessCallbackException extends Exception
{
public function __construct(\Closure $callback, $message = "", Exception $previous = null)
{
parent::__construct($message, 0, $previous);
$this->callback = $callback;
}
public $callback;
}
class AccessDeniedException extends ProcessCallbackException
{
public function __construct($message = null)
{
$f = function() {
return app()->redirect('/login');
};
parent::__construct($f, $message);
}
}
# Handle your special errors
$app->error(function (\Exception $e, $code) {
if ($e instanceof ProcessCallbackException)
{
/** #var ProcessCallbackException $callbackException */
$callbackException = $e;
return call_user_func($callbackException->callback);
}
else
return null;
});