如何使用@RestControllerAdvice全局处理异常(如ResourceNotFoundFoundException,NullPointerException等)?

时间:2019-03-31 10:55:50

标签: java spring-boot spring-data-jpa

我想全局处理异常,并使用ErrorResponse类返回自定义错误消息。

您可以建议我使用@RestControllerAdvice和ResponseEntity使用自定义错误消息处理异常的更好方法。

我尝试通过以下方式实现错误处理程序,但没有收到有关异常的自定义错误消息。

用户控制器:

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/users")
    public List<User> getall(){
       return userService.getAllUsers();
    }

    @GetMapping("/user/{id}")
    public User get(@PathVariable("id") String id){
       if (userService.getUser(id) == null)
            throw new ResourceNotFoundException(HttpStatus.NOT_FOUND, "User with provided Id is not found");
        return userService.getUser(id);
    }

    @PostMapping("/user/create")
    public ResponseEntity save(@RequestBody User user){
        user.setCreatedTime(LocalDate.now());
        user.setUpdatedTime(LocalDate.now());
        User savedUser = userService.createUser(user);
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("{id}")
                .buildAndExpand(savedUser.getId())
                .toUri();
        return ResponseEntity.created(location).build();
    }

    @PutMapping("/user/update")
    public User update(@RequestBody User user){
        user.setUpdatedTime(LocalDate.now());
        return userService.createUser(user);
    }

    @DeleteMapping("/user/delete/{id}")
    public void delete(@PathVariable("id") String id){
         userService.deleteUser(id);
    }
}

ResourceNotFoundException类:

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(HttpStatus statusCode, String message){
        super(message);
    }
}

CustomNullPointerException类:

public class CustomNullPointerException extends NullPointerException {
    public CustomNullPointerException(HttpStatus statusCode, String message){
        super(message);
    }
}

GlobalCustomExceptionHandling类:

@RestControllerAdvice
public class GlobalCustomExceptionHandling extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    protected ResponseEntity<ErrorMessage> handleAnyException(Exception ex, WebRequest req) {
        String errorMessageDescription = ex.getLocalizedMessage();
        if (errorMessageDescription == null)
            errorMessageDescription = ex.toString();
        ErrorMessage errorMessage = new ErrorMessage(LocalDate.now(),errorMessageDescription);
        return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = {ResourceNotFoundException.class})
    protected ResponseEntity<ErrorMessage> handleResourceNotFoundException(ResourceNotFoundException rnfex){
        String errorMessageDescription = rnfex.getLocalizedMessage();
        if (errorMessageDescription == null)
            errorMessageDescription = rnfex.toString();
        ErrorMessage errorMessage = new ErrorMessage(LocalDate.now(),errorMessageDescription);
        return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.NOT_FOUND);
    }

}

ErrorMessage类:

@Data
public class ErrorMessage {
    private LocalDate timestamp;
    private String message;
    public ErrorMessage(){}

    public ErrorMessage(LocalDate timestamp, String message) {
        this.timestamp = timestamp;
        this.message = message;
    }
}

实际结果:

{
   "timestamp": "2019-03-31",
   "message": "User with provided Id is not found"
}

预期结果:

{
   "timestamp": "2019-03-31",
   "status code": 404,
   "message": "User not found with Id 100"
}

0 个答案:

没有答案