46 行
1.8 KiB
Java
46 行
1.8 KiB
Java
|
|
package com.xuqm.im.controller;
|
||
|
|
|
||
|
|
import com.xuqm.common.exception.BusinessException;
|
||
|
|
import com.xuqm.common.model.ApiResponse;
|
||
|
|
import org.springframework.http.HttpStatus;
|
||
|
|
import org.springframework.http.ResponseEntity;
|
||
|
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||
|
|
|
||
|
|
@RestControllerAdvice
|
||
|
|
public class GlobalExceptionHandler {
|
||
|
|
|
||
|
|
@ExceptionHandler(BusinessException.class)
|
||
|
|
public ResponseEntity<ApiResponse<Void>> handleBusiness(BusinessException e) {
|
||
|
|
return ResponseEntity.status(resolveStatus(e.getCode()))
|
||
|
|
.body(ApiResponse.error(e.getCode(), e.getMessage()));
|
||
|
|
}
|
||
|
|
|
||
|
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||
|
|
public ResponseEntity<ApiResponse<Void>> handleValidation(MethodArgumentNotValidException e) {
|
||
|
|
return ResponseEntity.badRequest().body(ApiResponse.badRequest(e.getBindingResult()
|
||
|
|
.getFieldErrors()
|
||
|
|
.stream()
|
||
|
|
.findFirst()
|
||
|
|
.map(error -> error.getDefaultMessage())
|
||
|
|
.orElse("参数错误")));
|
||
|
|
}
|
||
|
|
|
||
|
|
@ExceptionHandler(Exception.class)
|
||
|
|
public ResponseEntity<ApiResponse<Void>> handleException(Exception e) {
|
||
|
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||
|
|
.body(ApiResponse.error(500, e.getMessage() == null ? "服务异常" : e.getMessage()));
|
||
|
|
}
|
||
|
|
|
||
|
|
private HttpStatus resolveStatus(int code) {
|
||
|
|
return switch (code) {
|
||
|
|
case 400 -> HttpStatus.BAD_REQUEST;
|
||
|
|
case 401 -> HttpStatus.UNAUTHORIZED;
|
||
|
|
case 403 -> HttpStatus.FORBIDDEN;
|
||
|
|
case 404 -> HttpStatus.NOT_FOUND;
|
||
|
|
default -> HttpStatus.INTERNAL_SERVER_ERROR;
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|