Monday, February 20, 2023

Exception handling in Spring using ErrorControler interface

 1) Using try and catch


Checked Exceptions needs to be handled by using try/catch or by using throws.


3) Template Pages

- Error code based HTML Pages

- Replaces the default whitelable page

- Can use template enginers like Thymeleaf of Spring

- pages can be static or dynamic 

- Best way is also is by using Spring Annotations (examples uses Spring 5 SDK)


3A) While label page - Below error came when user tried to access unavailable page


DANGERS OF ABOVE page:

it shows that application dont have /error page. 

As the page is not available it showed .. 

in case of exception at applicatoin, this shows all stack trace and exposes the sensitive info to user like below


 i) We can solve this also by using application.properties:by adding 


we get below without stack trace



ii) and by adding both as below we wont see the message also



as below



iii) We can also re-direct to default page in case of error (routing to default end point) . Below configuration server.error.path allows, when the error scenario occurs the default end point which is configured (here /people) will be called.

But the HTTP Error code is 500 (Internal Server error)


The above is works for REST ful interface (But if accessing web browser, the empty page will come but not the result of default end point). But it wont expose the stack trace and message. Becaue the error page while accessing using web browser is coming from Tomcat and not from applicatoin. (as below)

So, for error page tomcat configuratoin can be done.



4) To maintain same error information whether it is accessible using REST or Web interface: is 

in Spring is  implementing ErrorController interface.

which is our own Error Controller

Map the error page to error page so that all exceptions will point to the page Or error end point.

Here we can implement and return how we want it 

and

this is applicable for all error exceptions (Global error handling) . So that sensitive stack trace wont be exposed to the end user



using Browser


Using Postman REST



No comments:

Post a Comment