One thing that's quite convenient is to be able to throw an exception with a valid HTTP code set and have that code sent to the client.
For example, you may have:
throw new \RuntimeException("Not Found", 404);
With the standard Slim 4 error handler, this response is sent to the client:
$ curl -i -H "Accept:application/json" http://localhost:8888
HTTP/1.1 500 Internal Server Error
Host: localhost:8888
Content-type: application/json
{
"message": "Slim Application Error"
}
Ideally we want the status code to be 404.
Option 1: Use an HttpException
The simplest solution is to use one of Slim's HttpException classes:
use Slim\Exception\HttpNotFoundException;
...
throw new HttpNotFoundException($request);
This is only useful in a Request Handler as you need a Request object, but the expected response is sent to the client:
$ curl -i -H "Accept:application/json" http://localhost:8888
HTTP/1.1 404 Not Found
Host: localhost:8888
Content-type: application/json
{
"message": "404 Not Found"
}
Simple and easy!
Option 2: Override the ErrorMiddleware
There are situation when you can't simply replace the exception thrown. For example, you're updating an application from Slim 3 and you have hundreds of customised exceptions already throwing, or you throw from a class that doesn't have a Request object instance available.
In these cases, the easiest solution is to extend the Slim ErrorMiddleware to wrap the exception in an
HttpException
and then the standard error handling and rendering will "just work".
I'm feeling a little lazy, so let's use an anonymous class to do replace the call to $app->addErrorMiddleware():
$container = $app->getContainer();
$logger = $container->has(LoggerInterface::class) ?$container->get(LoggerInterface::class) : null;
$errorMiddleware = new class (
callableResolver: $app->getCallableResolver(),
responseFactory: $app->getResponseFactory(),
displayErrorDetails: false,
logErrors: true,
logErrorDetails: true,
logger: $logger
) extends \Slim\Middleware\ErrorMiddleware {
public function handleException(
ServerRequestInterface $request,
Throwable $exception
): \Psr\Http\Message\ResponseInterface
{
// determine that this exception should be wrapped. I'm checking for code between 400 & 599
if ($exception->getCode() >= 400 && $exception->getCode() < 600) {
// wrap the exception in an HttpException
$exception = new \Slim\Exception\HttpException(
$request,
$exception->getMessage(),
$exception->getCode(),
$exception
);
$exception->setTitle($exception->getMessage());
}
return parent::handleException($request, $exception);
}
};
$app->addMiddleware($errorMiddleware);
Behind the scenes of $app->addErrorMiddleware(), the \Slim\Middleware\ErrorMiddleware is constructed and then added to the middleware stack. We replicate that we an anonymous class that overrides handleException() to wrap the thrown exception if required.
Looking at the code in detail
There's quite a lot going on here, so let's break it down into parts.
$container = $app->getContainer();
$logger = $container->has(LoggerInterface::class) ?$container->get(LoggerInterface::class) : null;
$errorMiddleware = new class (
callableResolver: $app->getCallableResolver(),
responseFactory: $app->getResponseFactory(),
displayErrorDetails: false,
logErrors: true,
logErrorDetails: true,
logger: $logger
) extends \Slim\Middleware\ErrorMiddleware {
The constructor to \Slim\Middleware\ErrorMiddleware takes 6 parameters, so when we instantiate, we have to pass them all in though it's not unusual for the $logger parameter to be left off in the call to $app->addErrorMiddleware(). The easiest way to get a logger instance if there is one, is to grab it from the container where it should be registered under the \Psr\Log\LoggerInterface key which is imported into the file with a use statement.
I've used PHP 8's named arguments as this constructor takes three booleans and it's easier to remember what they do if they are label
Truncated by Planet PHP, read more at the original (another 2865 bytes)
We say it all the time because it’s true: CSS and JavaScript are capable of some amazing feats. Web-based animation is a prime example.
Not long ago, animation on the web was a bit rudimentary – save for add-on technology such as Flash. The movements were basic and often trended towards cartoonish. That’s not necessarily a bad thing, just not a great fit for every project.
What if you’re looking for something more realistic – almost cinematic in quality? These days, CSS and the right JavaScript library can help you get there.
To prove it, we’ve found some beautiful code snippets that bring an element of realism to web animation. They range from full-on recreations to examples that use a just hint of real-world effects. Enjoy!
You might also like our collection of Snippets for Creating Neumorphic UIs
Power On
The toggle switch has become a staple of web design – but this snippet takes things to another level. By adding a realistic surface and jittery backlight, this pure CSS animation looks like it belongs on a piece of machinery. Clicking the switch also produces a satisfying on/off effect.
See the Pen Realistic Red Switch (Pure CSS) by Yoav Kadosh
Something to Sea
A shimmering ocean. Dolphins playfully leaping. All of this was crafted with…JavaScript? That’s right. The special effects here are just stunning. The light dancing off the gentle waves, the natural movements, and impressive shadows are all powered by code.
See the Pen Dolphins at dawn 🐬 by Dilum
Looking Down
Here’s a unique example of parallax scrolling. The large bird’s eye view photo of a city is eye-catching in its own right. But move your cursor, and the perspective shifts as if you’re standing atop a building, looking down on the world below. It’s subtle but oh-so-cool.
See the Pen Bird’s Eye View Parallax by Sharna Hossain (@sharnajh)
Exploring Mother Earth
Taking things even further out into the stratosphere, this snippet offers an interactive look at Earth, powered by Three.js. Left to itself, the planet slowly spins while a field of stars moves in the background. But there’s more! Click and drag the screen to change the planet’s position to suit your liking. Hint: there’s a moon hidden in there somewhere.
See the Pen 3D Earth by Bryan Jones
Nintendo Switch Demo
This gaming device animation takes a different, and perhaps more classic, approach. A neumorphic Nintendo Switch acts as a container for a video from the popular game Animal Crossing: New Horizons. Put it all together, and it looks like the game is being played right in front of you.
See the Pen CSS Nintendo Switch (Box shadow + Gradient practice) by Elisabeth Diang
Subtle Smoke
The beauty of this snippet is in its subtlety. The hero area utilizes an attention-grabbing photo background of a volcano. Slow-moving wisps of smoke (powered by CSS) provide the perfect accent piece. It goes to show that the little details can make a world of difference.
See the Pen Animated hero image with CSS clipping by Mihael Tomić
Rays of Light
Driving through the mountains can be inspiring. This animation will bring some of that experience to your screen. It’s the lighting effects that really impress. As the sun rises and sets, check out the intensity, shadows, and movement. You can almost feel the heat!
See the Pen Solar Quartet – JS1K 2018 writeup by yonatan
Just Watch This
Those of us who grew up in the 1980s and 1990s will remember these digital watches. It seemed like every kid had one. Not only does this snippet recreate the look of a classic Casio, but it’s also interactive. Click the “Light” button on the upper left to get a nighttime view of the screen. Ah, the memories.
See the Pen CASIO F-91W with Pure CSS!! by Manz
Imagining a New Level of Reality
The examples above serve as a fun reminder of what’s possible when combining great tools with creativity. As languages, frameworks, and hardware evolve, realistic animation effects become more attainable.
Just think: in the early 2000s, a similar degree of realism would have taken some pretty robust software for both developers and users. Now, it can be built and viewed without a massive investment or buggy browser plugins.
We hope these snippets inspire you to level up your web animation projects. Want to see even more? Check out our CodePen collection for additional ideas.
The post 8 CSS & JavaScript Code Snippets for Creating Realistic Animation appeared first on Speckyboy Design Magazine.
Vim Bootstrap – This tool will generate a customized configuration based on your favorite programming languages for the Vim text editor.
Lineicons – Check out this collection of 5,000+ handcrafted, customizable line icons. Free and Pro versions available.
Bringing markers back to UI design – Add an authentic feel to your mockups with this free hand-drawn UI kit for Figma.
The State Of Web Workers In 2021 – How workers can help turn the web into a better performing, multithreaded application.
RTL:WTF – Experience the web in “reverse” with this tool that demonstrates how RTL works.
Towards richer colors on the Web – Learn about the ongoing efforts to specify richer colors on the Web platform.
It’s Task Management, Not Time Management – The main reason that you may not be getting enough done is not your time. It’s your to-do list.
Access Guide – Brush up on your #a11y skills with this friendly introduction to digital accessibility.
Windy – A React UI kit that’s powered by the popular Tailwind CSS framework.
How Taylor Arndt Brings a First-Person Perspective to Accessibility – If you really want to learn the ins and outs of accessibility, this expert is someone you’ll want to know.
CSS Layout Generator – Create your ideal layout in seconds with this handy online tool.
Tips for Finding Flow in Your Creative Process – A look at techniques that encourage your brain to get into that sweet creative flow.
Mondrian – An online tool for generating downloadable Mondrian patterns.
Dealing With Your Ego as a Designer – Why letting go of your ego can lead to better results.
Windframe – Check out this drag-and-drop page builder for Tailwind CSS.
Scenic – Download this free collection of 60+ animated backgrounds.
The post Weekly News for Designers № 601 appeared first on Speckyboy Design Magazine.