SlideShare a Scribd company logo
handle with
spring
Spring kullanmak bir REST API veya
mikro service geliştirme sürecini
hızlandırır ve API geliştiricilerinin
yalnızca temel iş sürecini yazmaya
odaklanmasına ve tüm temel
yapılandırmalar ve kurulum için
endişelenmenize izin vermez.
Server side
SERVER SIDE
@RestController annotation ile bir class oluşturun. Annotation
nedeniyle, bu class classpath scanning ile otomatik olarak
algılanacak ve @RequestMapping annotationı ile yazılan
method HTTP bitiş noktaları olarak gösterilecektir. Gelen bir
istek @RequestMapping annotationı ile belirtilen
gereksinimlerle eşleştiğinde, method requesti sunmak için
yürütülür.
Bir developerın bakış açısından, bir kullanıcı
listenin veritabanından alma akışı aşağıdaki
şekilde görülür:
 Bununla birlikte, Spring sahnelerin arkasında bizler için çok fazla iş
yaparken, her iki XML / JSON biçiminde yanıtı geri göndermek için bir
kaynağa bir HTTP request yapmak için tüm sürecin yaşam döngüsü bir
çok adım içerir.
 Bir requestte bulunduğunda, örneğin:
 Request : http: // localhost: 8080 / users
 Accept: application/json
 Bu gelen request, Spring tarafından otomatik olarak yapılandırılan
DispatcherServlet tarafından gerçekleştirilir.
Tüm gelen istekler tek bir servletten geçer: DispatcherServlet
Yeşilin içindeki bloklar, developer tarafından geliştirilen bloklardır.
Maviler ise Spring 
REST Serviceler İçin Spring ile Error Handling
 Spring 3.2'den önce, Spring exceptionları handle etmek için iki ana yaklaşım
şunlardı: HandlerExceptionResolver veya @ExceptionHandler annotationları.
Bunların her ikisinin de bazı olumsuz yönleri vardı.
 3.2'den beri, Spring önceki iki çözümün sınırlamalarını aşmak ve tüm bir
uygulama boyunca birleşik bir excption handling önermek için
@ControllerAdvice anotasyonuna sahip.
 Şimdi Spring 5, ResponseStatusException classına sahip: REST API’larımızda
temel error handling için hızlı bir yol.
Solution 1 – The Controller
level @ExceptionHandler
 @ExceptionHandler tüm uygulama için genel olarak değil, yalnızca bu belirli
method için etkindir.
1
2
3
4
5
6
7
8
public class FooController{
//...
@ExceptionHandler({ CustomException1.class,
CustomException2.class })
public void handleException() {
//
}
}
Solution 2 – The HandlerExceptionResolver
 İkinci çözüm bir HandlerExceptionResolver tanımlamaktır - bu, uygulamanın
attığı herhangi bir exeptionı handle edecektir. Ayrıca, REST API’mizde tek tip
bir exception handling mekanizması uygulamamıza izin verecektir.
 1. ExceptionHandlerExceptionResolver
 Bu handler Spring 3.1'de tanıtıldı ve default. @ExceptionHandler annotationın
temel bileşenidir.
 2. DefaultHandlerExceptionResolver
 Spring 3.0'da tanıtıldı ve default olarak DispatcherServlet'te etkinleştirildi.
Standart Spring exceptionlarını ilgili HTTP Status Kodlarına Client error – 4xx
and Server error – 5xx status codes. Çözümler.
 Tüm Exceptionları handle edip, HTTP kodları çözümlemesine rağmen hala bir
responsebody dönemiyordu. ModelAndView
Solution 2 – The HandlerExceptionResolver
 3.3. ResponseStatusExceptionResolver
 Bu handler Spring 3.0'da tanıtıldı ve default olarak DispatcherServlet'te etkin.
@ ResponseStatus Response statuslerine göre Custom exceptionları
implemente edebilmek için geliştirildi.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException
{
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message, Throwable
cause) {
super(message, cause);
}
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(Throwable cause) {
super(cause);
}
}
Solution 2 – The HandlerExceptionResolver
 3.3. ResponseStatusExceptionResolver
 Bu handler Spring 3.0'da tanıtıldı ve default olarak DispatcherServlet'te etkin.
@ ResponseStatus Response statuslerine göre Custom exceptionları
implemente edebilmek için geliştirildi.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException
{
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message, Throwable
cause) {
super(message, cause);
}
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(Throwable cause) {
super(cause);
}
}
Solution 2 – The HandlerExceptionResolver
 3.4. Custom HandlerExceptionResolver
 Custom exceptionlarla birlikte body de response a eklendi.
Solution 3 – @ControllerAdvice
 a global @ExceptionHandler with the @ControllerAdvice annotation
Solution 4 –
ResponseStatusException (Spring 5 and Above)
1
2
3
4
5
6
7
8
9
10
11
12
13
@GetMapping(value = "/{id}")
public Foo findById(@PathVariable("id") Long id,
HttpServletResponse response) {
try {
Foo resourceById =
RestPreconditions.checkFound(service.findOne(id));
eventPublisher.publishEvent(new
SingleResourceRetrievedEvent(this, response));
return resourceById;
}
catch (MyResourceNotFoundException exc) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Foo Not Found", exc);
}
}
Handle the Access Denied in Spring Security
 6.1. MVC – Custom Error Page
 customize an error page for Access Denied
<http>
<intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/>
...
<access-denied-handler error-page="/my-error-page" />
</http>
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
...
.and()
.exceptionHandling().accessDeniedPage("/my-error-page");
}
6.2. Custom AccessDeniedHandler
@Component
public class CustomAccessDeniedHandler implements
AccessDeniedHandler {
@Override
public void handle
(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException ex)
throws IOException, ServletException {
response.sendRedirect("/my-error-page");
}
}
6.2. Custom AccessDeniedHandler
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN")
...
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
}
6.3. REST and Method Level Security
1
2
3
4
5
6
7
8
9
10
11
12
13
@ControllerAdvice
public class RestResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler {
@ExceptionHandler({ AccessDeniedException.class })
public ResponseEntity<Object> handleAccessDeniedException(
Exception ex, WebRequest request) {
return new ResponseEntity<Object>(
"Access denied message here", new HttpHeaders(),
HttpStatus.FORBIDDEN);
}
...
}
7. Spring Boot Support
 Whitelabel Error Page with errors for browsers
 We can provide our own view-resolver mapping for /error, overriding the
Whitelabel Page
1
2
3
4
5
6
7
{
"timestamp": "2019-01-17T16:12:45.977+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Error processing the request!",
"path": "/my-endpoint-with-exceptions"
}
@Component
public class MyErrorController extends BasicErrorController {
public MyErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes, new ErrorProperties());
}
@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Map<String, Object>> xmlError(HttpServletRequest
request) {
// ...
}
}
Spring Retry
 Spring Retry, başarısız bir işlemi otomatik olarak yeniden başlatma yeteneği
sağlar. Bu, hataların doğada geçici olabileceği durumlarda yardımcı olur (anlık
bir ağ arızası gibi).
1
2
3
4
5
6
7
8
9
@Service
public interface MyService {
@Retryable(
value = { SQLException.class },
maxAttempts = 2,
backoff = @Backoff(delay = 5000))
void retryService(String sql) throws SQLException;
...
}
@Retyable
@Recover
1
2
3
4
5
6
@Service
public interface MyService {
...
@Recover
void recover(SQLException e, String sql);
}
RetryTemplate
1
2
3
4
5
public interface RetryOperations {
<T> T execute(RetryCallback<T> retryCallback) throws Exception;
...
}
1
2
3
public interface RetryCallback<T> {
T doWithRetry(RetryContext context) throws Throwable;
}
Spring Retry provides RetryOperations interface which supplies a set
of execute() methods:
The RetryCallback which is a parameter of the execute() is an interface that allows
insertion of business logic that needs to be retried upon failure:
RestTemplate Handling
 1. Default Error Handling
 HttpClientErrorException – in case of HTTP status 4xx
 HttpServerErrorException – in case of HTTP status 5xx
 UnknownHttpStatusCodeException – in case of an unknown HTTP status
 2. Implementing a ResponseErrorHandler
 Throw an exception that is meaningful to our application
 Simply ignore the HTTP status and let the response flow continue without
interruption
 demo
@Scheduled
1
2
3
4
5
@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
System.out.println(
"Fixed delay task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {
System.out.println(
"Fixed rate task - " + System.currentTimeMillis() / 1000);
}
Be careful about “Out of Memory”.
For configuration: https://www.baeldung.com/spring-
scheduled-tasks

More Related Content

What's hot

Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
Ahasanul Kalam Akib
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Http methods
Http methodsHttp methods
Http methods
maamir farooq
 
Microservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring CloudMicroservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring Cloud
Eberhard Wolff
 
Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)
Megan O'Keefe
 
Jenkins-CI
Jenkins-CIJenkins-CI
Jenkins-CI
Gong Haibing
 
Spring security
Spring securitySpring security
Spring security
Saurabh Sharma
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
Dragos Balan
 
Building layers of defense for your application
Building layers of defense for your applicationBuilding layers of defense for your application
Building layers of defense for your application
VMware Tanzu
 
Messaging with Spring Integration
Messaging with Spring IntegrationMessaging with Spring Integration
Messaging with Spring Integration
Vadim Mikhnevych
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
Prem Sanil
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Christopher Bartling
 
AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template Language
Gabriel Walt
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계
Wangeun Lee
 
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Edureka!
 
Getting Git
Getting GitGetting Git
Getting Git
Scott Chacon
 
Vault Open Source vs Enterprise v2
Vault Open Source vs Enterprise v2Vault Open Source vs Enterprise v2
Vault Open Source vs Enterprise v2
Stenio Ferreira
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
Jesus Perez Franco
 
Aem sling resolution
Aem sling resolutionAem sling resolution
Aem sling resolution
Gaurav Tiwari
 

What's hot (20)

Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Http methods
Http methodsHttp methods
Http methods
 
Microservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring CloudMicroservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring Cloud
 
Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)
 
Jenkins-CI
Jenkins-CIJenkins-CI
Jenkins-CI
 
Spring security
Spring securitySpring security
Spring security
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
 
Building layers of defense for your application
Building layers of defense for your applicationBuilding layers of defense for your application
Building layers of defense for your application
 
Messaging with Spring Integration
Messaging with Spring IntegrationMessaging with Spring Integration
Messaging with Spring Integration
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template Language
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계
 
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
 
Getting Git
Getting GitGetting Git
Getting Git
 
Vault Open Source vs Enterprise v2
Vault Open Source vs Enterprise v2Vault Open Source vs Enterprise v2
Vault Open Source vs Enterprise v2
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Aem sling resolution
Aem sling resolutionAem sling resolution
Aem sling resolution
 

Similar to Spring uygulamaların exception handling yönetimi

Yeni başlayanlar için Laravel
Yeni başlayanlar için Laravel Yeni başlayanlar için Laravel
Yeni başlayanlar için Laravel
Cüneyd Tural
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
Muharrem Tac
 
Mutant Web Applications
Mutant Web ApplicationsMutant Web Applications
Mutant Web Applications
guest096801
 
Asp.net mvc ve jquery ile sunucudan json verisi okuma
Asp.net mvc ve jquery ile sunucudan json verisi okumaAsp.net mvc ve jquery ile sunucudan json verisi okuma
Asp.net mvc ve jquery ile sunucudan json verisi okuma
erdemergin
 
Primeface
PrimefacePrimeface
Primeface
serserox
 
Socket Programming.pdf
Socket Programming.pdfSocket Programming.pdf
Socket Programming.pdf
YasinKabak
 
Java Web Uygulama Geliştirme
Java Web Uygulama GeliştirmeJava Web Uygulama Geliştirme
Java Web Uygulama Geliştirme
ahmetdemirelli
 
Spring Web Service
Spring Web ServiceSpring Web Service
Spring Web Service
dasgin
 
Emrah KAHRAMAN - Java RMI
Emrah KAHRAMAN - Java RMI Emrah KAHRAMAN - Java RMI
Emrah KAHRAMAN - Java RMI Emrah Kahraman
 
ASP.NET MVC'den ASP.NET Core MVC'ye Geçiş Süreci
ASP.NET MVC'den ASP.NET Core MVC'ye Geçiş SüreciASP.NET MVC'den ASP.NET Core MVC'ye Geçiş Süreci
ASP.NET MVC'den ASP.NET Core MVC'ye Geçiş Süreci
Sinan Bozkuş
 
Javascript Performance Optimisation
Javascript Performance OptimisationJavascript Performance Optimisation
Javascript Performance Optimisation
irfandurmus
 
Node js part 1 shared
Node js part 1 sharedNode js part 1 shared
Node js part 1 shared
Engin Yelgen
 
agem_intern_report
agem_intern_reportagem_intern_report
agem_intern_reportMeliz Ersoy
 
Java Server Faces
Java Server FacesJava Server Faces
Java Server Faces
ahmetdemirelli
 
Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3
Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3
Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3
BTRisk Bilgi Güvenliği ve BT Yönetişim Hizmetleri
 
Javascript - from past to present
Javascript - from past to present Javascript - from past to present
Javascript - from past to present
Kubilay TURAL
 
Oracle database architecture
Oracle database architectureOracle database architecture
Oracle database architecture
Hızlan ERPAK
 

Similar to Spring uygulamaların exception handling yönetimi (20)

Yeni başlayanlar için Laravel
Yeni başlayanlar için Laravel Yeni başlayanlar için Laravel
Yeni başlayanlar için Laravel
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Java EE Struts
Java EE StrutsJava EE Struts
Java EE Struts
 
Mutant Web Applications
Mutant Web ApplicationsMutant Web Applications
Mutant Web Applications
 
Asp.net mvc ve jquery ile sunucudan json verisi okuma
Asp.net mvc ve jquery ile sunucudan json verisi okumaAsp.net mvc ve jquery ile sunucudan json verisi okuma
Asp.net mvc ve jquery ile sunucudan json verisi okuma
 
Primeface
PrimefacePrimeface
Primeface
 
Socket Programming.pdf
Socket Programming.pdfSocket Programming.pdf
Socket Programming.pdf
 
sunu (Asp-2)
sunu (Asp-2)sunu (Asp-2)
sunu (Asp-2)
 
Java Web Uygulama Geliştirme
Java Web Uygulama GeliştirmeJava Web Uygulama Geliştirme
Java Web Uygulama Geliştirme
 
Spring Web Service
Spring Web ServiceSpring Web Service
Spring Web Service
 
Emrah KAHRAMAN - Java RMI
Emrah KAHRAMAN - Java RMI Emrah KAHRAMAN - Java RMI
Emrah KAHRAMAN - Java RMI
 
ASP.NET MVC'den ASP.NET Core MVC'ye Geçiş Süreci
ASP.NET MVC'den ASP.NET Core MVC'ye Geçiş SüreciASP.NET MVC'den ASP.NET Core MVC'ye Geçiş Süreci
ASP.NET MVC'den ASP.NET Core MVC'ye Geçiş Süreci
 
Javascript Performance Optimisation
Javascript Performance OptimisationJavascript Performance Optimisation
Javascript Performance Optimisation
 
Node js part 1 shared
Node js part 1 sharedNode js part 1 shared
Node js part 1 shared
 
agem_intern_report
agem_intern_reportagem_intern_report
agem_intern_report
 
Java Server Faces
Java Server FacesJava Server Faces
Java Server Faces
 
Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3
Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3
Uygulamali Sizma Testi (Pentest) Egitimi Sunumu - 3
 
Javascript - from past to present
Javascript - from past to present Javascript - from past to present
Javascript - from past to present
 
0439
04390439
0439
 
Oracle database architecture
Oracle database architectureOracle database architecture
Oracle database architecture
 

More from Sistek Yazılım

Event Driven Architecture
Event Driven ArchitectureEvent Driven Architecture
Event Driven Architecture
Sistek Yazılım
 
Javascript Today
Javascript TodayJavascript Today
Javascript Today
Sistek Yazılım
 
Amazon web service
Amazon web serviceAmazon web service
Amazon web service
Sistek Yazılım
 
Dekleratif Transaction Yönetimi
Dekleratif Transaction YönetimiDekleratif Transaction Yönetimi
Dekleratif Transaction Yönetimi
Sistek Yazılım
 
Dashboard Kit
Dashboard KitDashboard Kit
Dashboard Kit
Sistek Yazılım
 
So Bot
So BotSo Bot
Be Agile
Be AgileBe Agile
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Sistek Yazılım
 
Servlet Container Nedir?
Servlet Container Nedir?Servlet Container Nedir?
Servlet Container Nedir?
Sistek Yazılım
 
Hybrid Mobile Applications
Hybrid Mobile ApplicationsHybrid Mobile Applications
Hybrid Mobile Applications
Sistek Yazılım
 
No SQL & MongoDB Nedir?
No SQL & MongoDB Nedir?No SQL & MongoDB Nedir?
No SQL & MongoDB Nedir?
Sistek Yazılım
 

More from Sistek Yazılım (11)

Event Driven Architecture
Event Driven ArchitectureEvent Driven Architecture
Event Driven Architecture
 
Javascript Today
Javascript TodayJavascript Today
Javascript Today
 
Amazon web service
Amazon web serviceAmazon web service
Amazon web service
 
Dekleratif Transaction Yönetimi
Dekleratif Transaction YönetimiDekleratif Transaction Yönetimi
Dekleratif Transaction Yönetimi
 
Dashboard Kit
Dashboard KitDashboard Kit
Dashboard Kit
 
So Bot
So BotSo Bot
So Bot
 
Be Agile
Be AgileBe Agile
Be Agile
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Servlet Container Nedir?
Servlet Container Nedir?Servlet Container Nedir?
Servlet Container Nedir?
 
Hybrid Mobile Applications
Hybrid Mobile ApplicationsHybrid Mobile Applications
Hybrid Mobile Applications
 
No SQL & MongoDB Nedir?
No SQL & MongoDB Nedir?No SQL & MongoDB Nedir?
No SQL & MongoDB Nedir?
 

Spring uygulamaların exception handling yönetimi

  • 2. Spring kullanmak bir REST API veya mikro service geliştirme sürecini hızlandırır ve API geliştiricilerinin yalnızca temel iş sürecini yazmaya odaklanmasına ve tüm temel yapılandırmalar ve kurulum için endişelenmenize izin vermez.
  • 3. Server side SERVER SIDE @RestController annotation ile bir class oluşturun. Annotation nedeniyle, bu class classpath scanning ile otomatik olarak algılanacak ve @RequestMapping annotationı ile yazılan method HTTP bitiş noktaları olarak gösterilecektir. Gelen bir istek @RequestMapping annotationı ile belirtilen gereksinimlerle eşleştiğinde, method requesti sunmak için yürütülür.
  • 4. Bir developerın bakış açısından, bir kullanıcı listenin veritabanından alma akışı aşağıdaki şekilde görülür:
  • 5.  Bununla birlikte, Spring sahnelerin arkasında bizler için çok fazla iş yaparken, her iki XML / JSON biçiminde yanıtı geri göndermek için bir kaynağa bir HTTP request yapmak için tüm sürecin yaşam döngüsü bir çok adım içerir.  Bir requestte bulunduğunda, örneğin:  Request : http: // localhost: 8080 / users  Accept: application/json  Bu gelen request, Spring tarafından otomatik olarak yapılandırılan DispatcherServlet tarafından gerçekleştirilir.
  • 6. Tüm gelen istekler tek bir servletten geçer: DispatcherServlet Yeşilin içindeki bloklar, developer tarafından geliştirilen bloklardır. Maviler ise Spring 
  • 7. REST Serviceler İçin Spring ile Error Handling  Spring 3.2'den önce, Spring exceptionları handle etmek için iki ana yaklaşım şunlardı: HandlerExceptionResolver veya @ExceptionHandler annotationları. Bunların her ikisinin de bazı olumsuz yönleri vardı.  3.2'den beri, Spring önceki iki çözümün sınırlamalarını aşmak ve tüm bir uygulama boyunca birleşik bir excption handling önermek için @ControllerAdvice anotasyonuna sahip.  Şimdi Spring 5, ResponseStatusException classına sahip: REST API’larımızda temel error handling için hızlı bir yol.
  • 8. Solution 1 – The Controller level @ExceptionHandler  @ExceptionHandler tüm uygulama için genel olarak değil, yalnızca bu belirli method için etkindir. 1 2 3 4 5 6 7 8 public class FooController{ //... @ExceptionHandler({ CustomException1.class, CustomException2.class }) public void handleException() { // } }
  • 9. Solution 2 – The HandlerExceptionResolver  İkinci çözüm bir HandlerExceptionResolver tanımlamaktır - bu, uygulamanın attığı herhangi bir exeptionı handle edecektir. Ayrıca, REST API’mizde tek tip bir exception handling mekanizması uygulamamıza izin verecektir.  1. ExceptionHandlerExceptionResolver  Bu handler Spring 3.1'de tanıtıldı ve default. @ExceptionHandler annotationın temel bileşenidir.  2. DefaultHandlerExceptionResolver  Spring 3.0'da tanıtıldı ve default olarak DispatcherServlet'te etkinleştirildi. Standart Spring exceptionlarını ilgili HTTP Status Kodlarına Client error – 4xx and Server error – 5xx status codes. Çözümler.  Tüm Exceptionları handle edip, HTTP kodları çözümlemesine rağmen hala bir responsebody dönemiyordu. ModelAndView
  • 10. Solution 2 – The HandlerExceptionResolver  3.3. ResponseStatusExceptionResolver  Bu handler Spring 3.0'da tanıtıldı ve default olarak DispatcherServlet'te etkin. @ ResponseStatus Response statuslerine göre Custom exceptionları implemente edebilmek için geliştirildi. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException() { super(); } public ResourceNotFoundException(String message, Throwable cause) { super(message, cause); } public ResourceNotFoundException(String message) { super(message); } public ResourceNotFoundException(Throwable cause) { super(cause); } }
  • 11. Solution 2 – The HandlerExceptionResolver  3.3. ResponseStatusExceptionResolver  Bu handler Spring 3.0'da tanıtıldı ve default olarak DispatcherServlet'te etkin. @ ResponseStatus Response statuslerine göre Custom exceptionları implemente edebilmek için geliştirildi. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException() { super(); } public ResourceNotFoundException(String message, Throwable cause) { super(message, cause); } public ResourceNotFoundException(String message) { super(message); } public ResourceNotFoundException(Throwable cause) { super(cause); } }
  • 12. Solution 2 – The HandlerExceptionResolver  3.4. Custom HandlerExceptionResolver  Custom exceptionlarla birlikte body de response a eklendi. Solution 3 – @ControllerAdvice  a global @ExceptionHandler with the @ControllerAdvice annotation
  • 13. Solution 4 – ResponseStatusException (Spring 5 and Above) 1 2 3 4 5 6 7 8 9 10 11 12 13 @GetMapping(value = "/{id}") public Foo findById(@PathVariable("id") Long id, HttpServletResponse response) { try { Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); return resourceById; } catch (MyResourceNotFoundException exc) { throw new ResponseStatusException( HttpStatus.NOT_FOUND, "Foo Not Found", exc); } }
  • 14. Handle the Access Denied in Spring Security  6.1. MVC – Custom Error Page  customize an error page for Access Denied <http> <intercept-url pattern="/admin/*" access="hasAnyRole('ROLE_ADMIN')"/> ... <access-denied-handler error-page="/my-error-page" /> </http> @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") ... .and() .exceptionHandling().accessDeniedPage("/my-error-page"); }
  • 15. 6.2. Custom AccessDeniedHandler @Component public class CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle (HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException { response.sendRedirect("/my-error-page"); } }
  • 16. 6.2. Custom AccessDeniedHandler @Autowired private CustomAccessDeniedHandler accessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") ... .and() .exceptionHandling().accessDeniedHandler(accessDeniedHandler) }
  • 17. 6.3. REST and Method Level Security 1 2 3 4 5 6 7 8 9 10 11 12 13 @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler({ AccessDeniedException.class }) public ResponseEntity<Object> handleAccessDeniedException( Exception ex, WebRequest request) { return new ResponseEntity<Object>( "Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN); } ... }
  • 18. 7. Spring Boot Support  Whitelabel Error Page with errors for browsers  We can provide our own view-resolver mapping for /error, overriding the Whitelabel Page 1 2 3 4 5 6 7 { "timestamp": "2019-01-17T16:12:45.977+0000", "status": 500, "error": "Internal Server Error", "message": "Error processing the request!", "path": "/my-endpoint-with-exceptions" }
  • 19. @Component public class MyErrorController extends BasicErrorController { public MyErrorController(ErrorAttributes errorAttributes) { super(errorAttributes, new ErrorProperties()); } @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE) public ResponseEntity<Map<String, Object>> xmlError(HttpServletRequest request) { // ... } }
  • 20. Spring Retry  Spring Retry, başarısız bir işlemi otomatik olarak yeniden başlatma yeteneği sağlar. Bu, hataların doğada geçici olabileceği durumlarda yardımcı olur (anlık bir ağ arızası gibi). 1 2 3 4 5 6 7 8 9 @Service public interface MyService { @Retryable( value = { SQLException.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000)) void retryService(String sql) throws SQLException; ... } @Retyable
  • 21. @Recover 1 2 3 4 5 6 @Service public interface MyService { ... @Recover void recover(SQLException e, String sql); }
  • 22. RetryTemplate 1 2 3 4 5 public interface RetryOperations { <T> T execute(RetryCallback<T> retryCallback) throws Exception; ... } 1 2 3 public interface RetryCallback<T> { T doWithRetry(RetryContext context) throws Throwable; } Spring Retry provides RetryOperations interface which supplies a set of execute() methods: The RetryCallback which is a parameter of the execute() is an interface that allows insertion of business logic that needs to be retried upon failure:
  • 23. RestTemplate Handling  1. Default Error Handling  HttpClientErrorException – in case of HTTP status 4xx  HttpServerErrorException – in case of HTTP status 5xx  UnknownHttpStatusCodeException – in case of an unknown HTTP status  2. Implementing a ResponseErrorHandler  Throw an exception that is meaningful to our application  Simply ignore the HTTP status and let the response flow continue without interruption  demo
  • 24. @Scheduled 1 2 3 4 5 @Scheduled(fixedDelay = 1000) public void scheduleFixedDelayTask() { System.out.println( "Fixed delay task - " + System.currentTimeMillis() / 1000); } @Scheduled(fixedRate = 1000) public void scheduleFixedRateTask() { System.out.println( "Fixed rate task - " + System.currentTimeMillis() / 1000); } Be careful about “Out of Memory”. For configuration: https://www.baeldung.com/spring- scheduled-tasks