1

I created One restful Api which has all the crud operations. when i am testing get employee By id i am not able to display error message. even though i am throwing exception when record not exists for that id.

Here is My Controller code...

    @GetMapping("/employee/{id}")
    public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") long employeeId) throws ResourceNotFoundException{

        Employee employee=service.getEmployeeById(employeeId).orElseThrow(()->new ResourceNotFoundException("Employee not found for this id :"+employeeId));

        return new ResponseEntity<Employee>(employee, HttpStatus.OK);

and My Exception class code

package com.mystyle.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    public ResourceNotFoundException(String message){
        super(message);
    }
}

and my postman error message

{
    "timestamp": "2020-05-19T06:21:10.172+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/api/v1/employee/2"
}
4

1 回答 1

0
  1. 在模型包下为错误消息创建一个类。
 public class ErrorMessage {

  private String errorMessage;
  private int errorCode;
  private String documentation;
  public ErrorMessage() {

  }
  public ErrorMessage(String errorMessage, int errorCode, String documentation) {
      this.errorMessage = errorMessage;
      this.errorCode = errorCode;
      this.documentation = documentation;
  }
  public String getErrorMessage() {
      return errorMessage;
  }
  public void setErrorMessage(String errorMessage) {
      this.errorMessage = errorMessage;
  }
  public int getErrorCode() {
      return errorCode;
  }
  public void setErrorCode(int errorCode) {
      this.errorCode = errorCode;
  }
  public String getDocumentation() {
      return documentation;
  }
  public void setDocumentation(String documentation) {
      this.documentation = documentation;
  }

   }

2.在异常包下创建Custome Exception类,生成Serial Version UID。

public class ResourceNotFoundException extends RuntimeException{

    /**
     * 
     */
    private static final long serialVersionUID = -2491065979792776613L;

    public ResourceNotFoundException(String msg)
    {
        super(msg);
    }

}

3.在异常包下创建ExceptionHandler类

@RestControllerAdvice
public class ResourceNotFoundExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorMessage> toResponse(ResourceNotFoundException ex)
    {
        ErrorMessage errorMessage=new ErrorMessage(ex.getMessage(),404,"www.benz.com");

        return new ResponseEntity<ErrorMessage>(errorMessage,HttpStatus.NOT_FOUND);
    }
}
于 2020-05-19T08:05:48.967 回答