當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot文档阅读笔记-exception handling–@ExceptionHandler解析与实例
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot文档阅读笔记-exception handling–@ExceptionHandler解析与实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序結構如下:
源碼如下:
CustomExceptionHandler.java
package com.example.demo.controller;import com.example.demo.exception.RecordNotFoundException; import com.example.demo.object.ErrorResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;import java.util.ArrayList; import java.util.List; import java.util.Map;@SuppressWarnings({"unchecked", "rawtypes"}) @ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler {@ExceptionHandler(Exception.class)public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request){List<String> details = new ArrayList<>();details.add(ex.getLocalizedMessage());ErrorResponse error = new ErrorResponse("Server Error", details);return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);}@ExceptionHandler(RecordNotFoundException.class)public final ResponseEntity<Object> handleUserNotFoundException(RecordNotFoundException ex, WebRequest request){List<String> detail = new ArrayList<>();detail.add(ex.getLocalizedMessage());ErrorResponse error = new ErrorResponse("Record Not Found", detail);return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);}@Overrideprotected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {List<String> details = new ArrayList<>();for(ObjectError error : ex.getBindingResult().getAllErrors()){details.add(error.getDefaultMessage());}ErrorResponse error = new ErrorResponse("Validation Failed", details);return new ResponseEntity(error, HttpStatus.BAD_REQUEST);} }MyController.java
package com.example.demo.controller;import com.example.demo.exception.RecordNotFoundException; import com.example.demo.object.EmployeeVO; import com.example.demo.repository.EmployeeDB; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;import javax.validation.Valid;@RestController public class MyController {@PostMapping(value = "/employees")public ResponseEntity<EmployeeVO> addEmployee(@Valid @RequestBody EmployeeVO employeeVO){EmployeeDB.addEmployee(employeeVO);return new ResponseEntity<EmployeeVO>(employeeVO, HttpStatus.OK);}@GetMapping(value = "/employees/{id}")public ResponseEntity<EmployeeVO> getEmployeeById(@PathVariable("id") Integer id){EmployeeVO employeeById = EmployeeDB.getEmployeeById(id);if(employeeById == null){throw new RecordNotFoundException("Invalid employee id : " + id);}return new ResponseEntity<EmployeeVO>(employeeById, HttpStatus.OK);} }RecordNotFoundException.java
package com.example.demo.exception;import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus;@ResponseStatus(HttpStatus.NOT_FOUND) public class RecordNotFoundException extends RuntimeException {public RecordNotFoundException(String exception){super(exception);} }EmployeeVO.java
package com.example.demo.object;import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable;@XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.FIELD) public class EmployeeVO implements Serializable {private static final long serialVersionUID = 1L;private Integer employeeId;@NotEmpty(message = "first name must not be empty")private String firstName;@NotEmpty(message = "last name must not be empty")private String lastName;@NotEmpty(message = "email must not be empty")@Email(message = "email should be a valid email")private String email;public EmployeeVO(Integer employeeId, String firstName, String lastName, String email) {super();this.employeeId = employeeId;this.firstName = firstName;this.lastName = lastName;this.email = email;}public EmployeeVO() {}public Integer getEmployeeId() {return employeeId;}public void setEmployeeId(Integer employeeId) {this.employeeId = employeeId;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;} }ErrorResponse.java
package com.example.demo.object;import javax.xml.bind.annotation.XmlRootElement; import java.util.List;@XmlRootElement(name = "error") public class ErrorResponse {private String message;private List<String> details;public ErrorResponse(String message, List<String> details) {this.message = message;this.details = details;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public List<String> getDetails() {return details;}public void setDetails(List<String> details) {this.details = details;} }EmployeeDB.java
package com.example.demo.repository;import com.example.demo.object.EmployeeVO;import java.util.ArrayList;public class EmployeeDB {private static ArrayList<EmployeeVO> employeeVOArrayList = new ArrayList<>();public static void addEmployee(EmployeeVO employeeVO){employeeVOArrayList.add(employeeVO);}public static EmployeeVO getEmployeeById(Integer id){for(EmployeeVO item : employeeVOArrayList){if(item.getEmployeeId().equals(id)){return item;}}return null;} }DemoApplication.java
package com.example.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);}}測試:
1) HTTP GET /employees/1 [VALID]
HTTP Status : 200{"employeeId": 1,"firstName": "John","lastName": "Wick","email": "howtodoinjava@gmail.com", }2) HTTP GET /employees/23 [INVALID]
HTTP Status : 404{"message": "Record Not Found","details": ["Invalid employee id : 23"] }3) HTTP POST /employees [INVALID]
Request
{"lastName": "Bill","email": "ibill@gmail.com" }Response
HTTP Status : 400{"message": "Validation Failed","details": ["first name must not be empty"] }4) HTTP POST /employees [INVALID]
Request
{"email": "ibill@gmail.com" }Response
HTTP Status : 400{"message": "Validation Failed","details": ["last name must not be empty","first name must not be empty"] }5) HTTP POST /employees [INVALID]
Request
{"firstName":"Lokesh","email": "ibill_gmail.com" //invalid email in request }Response
HTTP Status : 400{"message": "Validation Failed","details": ["last name must not be empty","email should be a valid email"] }源碼打包下載地址:
https://github.com/fengfanchen/Java/tree/master/ErrorHandling
總結
以上是生活随笔為你收集整理的Spring Boot文档阅读笔记-exception handling–@ExceptionHandler解析与实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue笔记-Ant Design Vue
- 下一篇: Qt工作笔记-Qt5中中文编码方面的笔记