Spring Boot文档阅读笔记-exception handling–@ExceptionHandler解析与实例

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }


    @Override
    protected 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解析与实例的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot文档阅读笔记-Scheduling Tasks

Spring Boot文档阅读笔记-exception handling–@ExceptionHandler解析与实例

Spring Boot文档阅读笔记-CORS Support

Spring Boot文档阅读笔记-CORS Support

Spring Boot文档阅读笔记-CORS Support

Spring Boot文档阅读笔记-how-to-implement-2-way-ssl-using-spring-boot