التعامل مع الاستثناءات في الإقلاع او التمهيد الربيع Spring Boot Exception Handling#

التعامل مع الاستثناءات في الإقلاع او التمهيد الربيع

 Spring Boot Exception Handling#

التعامل مع الاستثناءات في الإقلاع او التمهيد الربيع Spring Boot Exception Handling#

يعد التعامل مع الاستثناءات والأخطاء في واجهات برمجة التطبيقات وإرسال الاستجابة المناسبة إلى العميل مفيدًا لتطبيقات المؤسسات.  في هذا الفصل ، سوف نتعلم كيفية التعامل مع الاستثناءات في Spring Boot.

 قبل الشروع في معالجة الاستثناءات ، دعونا نتعرف على التعليقات التوضيحية التالية.

 نصيحة المراقب المالي
 ControllerAdvice هو تعليق توضيحي ، لمعالجة الاستثناءات على مستوى العالم.

معالج استثناء
 ExceptionHandler هو تعليق توضيحي يستخدم لمعالجة الاستثناءات المحددة وإرسال ردود العميل المخصصة.

 يمكنك استخدام التعليمات البرمجية التالية لإنشاء فئةControllerAdvice لمعالجة الاستثناءات على مستوى العالم -

package com.ahmedalmahallawi.demo.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;

@ControllerAdvice
   public class ProductExceptionController {
}
تحديد فئة يمتد فئة RuntimeException.

package com.ahmedalmahallawi.demo.exception;

public class ProductNotfoundException extends RuntimeException {
   private static final long serialVersionUID = 1L;
}

يمكنك تحديد طريقةExceptionHandler لمعالجة الاستثناءات كما هو موضح.  يجب استخدام هذه الطريقة لكتابة ملف فئة Controller Controller.

@ExceptionHandler(value = ProductNotfoundException.class)

public ResponseEntity<Object> exception(ProductNotfoundException exception) {
}
الآن ، استخدم الكود الوارد أدناه لإلقاء الاستثناء من واجهة برمجة التطبيقات.
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct() { 
   throw new ProductNotfoundException();
}
ويرد رمز كامل للتعامل مع الاستثناء أدناه.  في هذا المثال ، استخدمنا PUT API لتحديث المنتج.  هنا ، أثناء تحديث المنتج ، إذا لم يتم العثور على المنتج ، فقم بإرجاع رسالة خطأ الاستجابة كـ "المنتج غير موجود".  لاحظ أن فئة الاستثناء ProductNotFoundException يجب توسيع RuntimeException.

package com.ahmedalmahallawi.demo.exception;
public class ProductNotfoundException extends RuntimeException {
   private static final long serialVersionUID = 1L;
}
فيما يلي فئة مشورة المراقب المالي للتعامل مع الاستثناء على المستوى العالمي.  يمكننا تحديد أي أساليب معالج استثناء في هذا الملف فئة.

package com.ahmedalmahallawi.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ProductExceptionController {
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException exception) {
      return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
   }
}

يتم توفير ملف وحدة تحكم API Service Service أدناه لتحديث المنتج.  إذا لم يتم العثور على المنتج ، فإنه يلقي فئة ProductNotFoundException.
package com.ahmedalmahallawi.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);
      
      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }
   
   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { 
      if(!productRepo.containsKey(id))throw new ProductNotfoundException();
      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
      return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK);
   }
}
فيما يلي رمز ملف فئة تطبيق Spring Boot الرئيسي -

package com.ahmedalmahallawi.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}
رمز الفئة POJO للمنتج موضح أدناه -

package com.ahmedalmahallawi.demo.model;
public class Product {
   private String id;
   private String name;

   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
يظهر رمز Maven build - pom.xml أدناه -

xml version = "1.0" encoding = "UTF-8"?>
 xmlns = "http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   4.0.0
com.ahmedalmahallawi demo 0.0.1-SNAPSHOT jar demo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.8.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin

رمز Gradle Build - build.gradle مبين أدناه -

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

يمكنك إنشاء ملف JAR قابل للتنفيذ ، وتشغيل تطبيق Spring Boot باستخدام أوامر Maven أو Gradle -

 بالنسبة إلى Maven ، يمكنك استخدام الأمر التالي -
mvn clean install

بعد "بناء النجاح" ، يمكنك العثور على ملف JAR ضمن الدليل الهدف.

 بالنسبة إلى Gradle ، يمكنك استخدام الأمر التالي -
gradle clean build

بعد "BUILD SUCCESSFUL" ، يمكنك العثور على ملف JAR ضمن دليل build / libs.

 يمكنك تشغيل ملف JAR باستخدام الأمر التالي -

java –jar 

سيؤدي هذا إلى تشغيل التطبيق على منفذ Tomcat 8080 كما هو موضح أدناه -


الآن اضغط على الرابط أدناه في تطبيق POSTMAN ويمكنك أن ترى الإخراج كما هو موضح أدناه -

 تحديث URL: http: // localhost: 8080 / products / 3